pull解析xml文件,和sax和dom一样 都可以脱离android单独使用,pull和sax的原理一样,不一样的地方是pull读取xml文件后调用方法返回的是数字,
读取到xml的声明返回数字0 START_DOCUMENT;
读取到xml的结束返回数字1 END_DOCUMENT ;
读取到xml的开始标签返回数字2 START_TAG
读取到xml的结束标签返回数字3 END_TAG
读取到xml的文本返回数字4 TEXT
pull是开源的项目 源码下载地址http://www.xmlpull.org/
service中的代码
<!--EndFragment-->
利用pull创建xml文件
public static void writeXml(List<Person> persons, Writer writer) throws Exception{
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);//<?xml version="1.0" encoding="UTF-8"?>
serializer.startTag(null, "persons");
for(Person person : persons){
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();
writer.flush();
writer.close();
}
写入xml文件测试
StringWriter writer = new StringWriter();
List<Person> persons = new ArrayList<Person>();
persons.add(new Person(12, "李明", new Short((short)36)));
persons.add(new Person(78, "老张", new Short((short)26)));
persons.add(new Person(90, "老毕", new Short((short)16)));
PullPersonService.writeXml(persons, writer);
Log.i(TAG, writer.toString());