Pull解析器只有一个重要的方法next(),它的事件也只有5个(START_DOCUMENT,START_TAG,TEXT,END_TAG,END_DOCUMENT)解析方法类似于SAX。
代码如下:
public class PullPersonService { public static List<Person> getPersons(InputStream inputStream) throws Exception{ Person person = null; List<Person> list = null; XmlPullParser pullParser = Xml.newPullParser(); pullParser.setInput(inputStream, "UTF-8"); int event = pullParser.getEventType();//触发第一个事件 while (event != XmlPullParser.END_DOCUMENT) { switch (event) { case XmlPullParser.START_DOCUMENT: list = new ArrayList<Person>(); break; case XmlPullParser.START_TAG: if("person".equals(pullParser.getName())){ int id = Integer.valueOf(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())); Log.i("TAG", person.toString()); } } break; case XmlPullParser.END_TAG: if("person".equals(pullParser.getName())){ list.add(person); person = null; } break; } event = pullParser.next(); } return list; } }
public static void save(List<Person> list, OutputStream outputStream) throws Exception{ XmlSerializer serializer = Xml.newSerializer();//对象序列化 serializer.setOutput(outputStream, "UTF-8"); serializer.startDocument("UTF-8", true); serializer.startTag(null, "persons"); for (Person person : list) { serializer.startTag(null, "person"); serializer.attribute(null, "id", String.valueOf(person.getId())); serializer.startTag(null, "name"); serializer.text(person.getName()); serializer.endTag(null, "name"); serializer.startTag(null, "age"); serializer.text(String.valueOf(person.getAge())); serializer.endTag(null, "age"); serializer.endTag(null, "person"); } serializer.endTag(null, "persons"); serializer.endDocument(); outputStream.flush(); outputStream.close(); }