首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > XML SOAP >

Android范例系列-05.三种解析XML的方法

2013-01-22 
Android实例系列---05.三种解析XML的方法Android中三种解析XML的方法SAX DOM PULL,推荐使用PULL0.xml文件

Android实例系列---05.三种解析XML的方法

Android中三种解析XML的方法SAX DOM PULL,推荐使用PULL

0.xml文件

<?xml version="1.0" encoding="UTF-8"?><persons><person id="23"><name>李明</name><age>30</age></person><person id="20"><name>李向梅</name><age>25</age></person></persons>
?

1.SAX

public class SAXPersonService {public List<Person> getPersons(InputStream inStream) throws Throwable{SAXParserFactory factory = SAXParserFactory.newInstance();SAXParser parser = factory.newSAXParser();PersonParser personParser = new PersonParser();parser.parse(inStream, personParser);inStream.close();return personParser.getPersons();}private final class PersonParser extends DefaultHandler{private List<Person> persons = null;private String tag = null;private Person person = null;public List<Person> getPersons() {return persons;}@Overridepublic void startDocument() throws SAXException {persons = new ArrayList<Person>();}@Overridepublic void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {if("person".equals(localName)){person = new Person();person.setId(new Integer(attributes.getValue(0)));}tag = localName;}@Overridepublic void characters(char[] ch, int start, int length)throws SAXException {if(tag!=null){String data = new String(ch, start, length);//获取文本节点的数据if("name".equals(tag)){person.setName(data);}else if("age".equals(tag)){person.setAge(new Short(data));}}}@Overridepublic void endElement(String uri, String localName, String qName)throws SAXException {if("person".equals(localName)){persons.add(person);person = null;}tag = null;}}}

?2.DOM

?

public class DOMPersonService {public static List<Person> getPersons(InputStream inStream) throws Throwable{List<Person> persons = new ArrayList<Person>();DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();DocumentBuilder builder = factory.newDocumentBuilder();Document documnet = builder.parse(inStream);Element root = documnet.getDocumentElement();NodeList personNodes = root.getElementsByTagName("person");for(int i=0 ; i < personNodes.getLength(); i++){Person person = new Person();Element personElement = (Element)personNodes.item(i);person.setId(new Integer(personElement.getAttribute("id")));NodeList personChilds = personElement.getChildNodes();for(int y=0 ; y < personChilds.getLength(); y++){if(personChilds.item(y).getNodeType()==Node.ELEMENT_NODE){//判断当前节点是否是元素类型节点Element childElement = (Element)personChilds.item(y);if("name".equals(childElement.getNodeName())){person.setName(childElement.getFirstChild().getNodeValue());}else if("age".equals(childElement.getNodeName())){person.setAge(new Short(childElement.getFirstChild().getNodeValue()));}}}persons.add(person);}return persons;}}

?3.Pull

?

public class PULLPersonService {public static void save(List<Person> persons, Writer writer) throws Throwable{XmlSerializer serializer = Xml.newSerializer();serializer.setOutput(writer);serializer.startDocument("UTF-8", true);serializer.startTag(null, "persons");for(Person person : persons){serializer.startTag(null, "person");serializer.attribute(null, "id", person.getId().toString());serializer.startTag(null, "name");serializer.text(person.getName());serializer.endTag(null, "name");serializer.startTag(null, "age");serializer.text(person.getAge().toString());serializer.endTag(null, "age");serializer.endTag(null, "person");}serializer.endTag(null, "persons");serializer.endDocument();writer.flush();writer.close();}public static List<Person> getPersons(InputStream inStream) throws Throwable{List<Person> persons = null;Person person = null;XmlPullParser parser = Xml.newPullParser();parser.setInput(inStream, "UTF-8");int eventType = parser.getEventType();//产生第一个事件while(eventType!=XmlPullParser.END_DOCUMENT){//只要不是文档结束事件switch (eventType) {case XmlPullParser.START_DOCUMENT:persons = new ArrayList<Person>();break;case XmlPullParser.START_TAG:String name = parser.getName();//获取解析器当前指向的元素的名称if("person".equals(name)){person = new Person();person.setId(new Integer(parser.getAttributeValue(0)));}if(person!=null){if("name".equals(name)){person.setName(parser.nextText());//获取解析器当前指向元素的下一个文本节点的值}if("age".equals(name)){person.setAge(new Short(parser.nextText()));}}break;case XmlPullParser.END_TAG:if("person".equals(parser.getName())){persons.add(person);person = null;}break;}eventType = parser.next();}return persons;}}

? 测试类

?

public class PersonServiceTest extends AndroidTestCase {private static final String TAG = "PersonServiceTest";public void testSAXGetPersons() throws Throwable{SAXPersonService service = new SAXPersonService();InputStream inStream = getClass().getClassLoader().getResourceAsStream("itcast.xml");List<Person> persons = service.getPersons(inStream);for(Person person : persons){Log.i(TAG, person.toString());    }}public void testDomGetPersons() throws Throwable{InputStream inStream = getClass().getClassLoader().getResourceAsStream("itcast.xml");List<Person> persons = DOMPersonService.getPersons(inStream);for(Person person : persons){Log.i(TAG, person.toString());}}public void testPullGetPersons() throws Throwable{InputStream inStream = getClass().getClassLoader().getResourceAsStream("itcast.xml");List<Person> persons = PULLPersonService.getPersons(inStream);for(Person person : persons){Log.i(TAG, person.toString());}}public void testSave() throws Throwable{//File file = new File(this.getContext().getFilesDir(), "person.xml");//FileOutputStream outStream = new FileOutputStream(file);List<Person> persons = new ArrayList<Person>();persons.add(new Person(34, "lili", (short)12));persons.add(new Person(56, "老毕", (short)32));persons.add(new Person(39, "老张", (short)40));/*FileOutputStream outStream = this.getContext().openFileOutput("person.xml", Context.MODE_PRIVATE);OutputStreamWriter writer = new OutputStreamWriter(outStream, "UTF-8");BufferedWriter bWriter = new BufferedWriter(writer);*/StringWriter writer = new StringWriter();PULLPersonService.save(persons, writer);Log.i(TAG, writer.toString());}}

热点排行