XmlPullParser.START_DOCUMENT;(开始对文档的解析) XmlPullParser.START_TAG;(开始对元素的解析) XmlPullParser.TEXT;(解析文本) XmlPullParser.END_TAG;(开始对元素的解析) XmlPullParser.END_DOCUMENT;(结束对文档的解析)最常用的方法是:
parser.getEventType(); // 触发事件,开始解析 parser.next(); // 解析下一个事件 parser.getAttributeValue(); //获得相应属性的值
步骤不多说,序列化,得到方法,设置参数,开始解析。示例代码如下:
public static List<Person> getPersons(InputStream inStream) throws Exception{ Person person = null; List<Person> persons = null; XmlPullParser pullParser = Xml.newPullParser(); pullParser.setInput(inStream, "UTF-8"); int event = pullParser.getEventType();//触发第一个事件 while(event!=XmlPullParser.END_DOCUMENT){ switch (event) { case XmlPullParser.START_DOCUMENT: persons = new ArrayList<Person>(); break; case XmlPullParser.START_TAG: if("person".equals(pullParser.getName())){ int id = new Integer(pullParser.getAttributeValue(0)); person = new Person(); person.setId(id); } if(person!=null){ if("name".equals(pullParser.getName())){ person.setName(pullParser.nextText()); } if("age".equals(pullParser.getName())){ person.setAge(new Short(pullParser.nextText())); } } break; case XmlPullParser.END_TAG: if("person".equals(pullParser.getName())){ persons.add(person); person = null; } break; } event = pullParser.next(); } return persons; }
在SAX对XML文档的解析中,我们提到过,SAX解析不支持文件的修改、生成,那么Pull解析呢?Pull解析是支持对文件的修改的。
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(outStream, "UTF-8"); serializer.startDocument("UTF-8", true);
serializer.startTag(null, "persons"); serializer.endTag(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"); }
outStream.flush(); outStream.close();
原文地址:http://blog.csdn.net/ljtyzhr/article/details/40892467