这篇文章主要为大家展示了“Pull方式解析XML的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Pull方式解析XML的示例分析”这篇文章吧。
目前创新互联已为近1000家的企业提供了网站建设、域名、虚拟空间、网站托管运营、企业网站设计、巢湖网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。
Pull方式解析XML
1、XML文件
liming 30 lixiangmei 25
2、实体类
package com.example.pullparsexml; public class Person { private Integer id; private String name; private Short age; public Person(){} public Person(Integer id, String name, Short age) { this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Short getAge() { return age; } public void setAge(Short age) { this.age = age; } @Override public String toString() { return "Person [age=" + age + ", id=" + id + ", name=" + name + "]"; } }
3、代码实现
package com.example.pullparsexml; import java.io.InputStream; import java.io.Writer; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlSerializer; import android.util.Xml; public class PullParseXML { public static void save(Listpersons, 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 getPersons(InputStream inStream) throws Throwable { List 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 (); 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; } }
以上是“Pull方式解析XML的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!