一、基本介绍Android中极力推荐xmlpull方式解析xml。
xmlpull不仅可用在Android上同样也适用于javase,但在javase环境中需自己获取xmlpull所依赖的类库,kxml2-2.3.0.jar,xmlpull_1_1_3_4c.jar。jar包下载网址
http://www.xmlpull.org/http://kxml.sourceforge.net/
二、例子
读取到xml的声明返回数字0 START_DOCUMENT;
读取到xml的结束返回数字1 END_DOCUMENT ; 读取到xml的开始标签返回数字2 START_TAG 读取到xml的结束标签返回数字3 END_TAG 读取到xml的文本返回数字4 TEXT- <?xml version="1.0" encoding="UTF-8"?>
- <people>
- <person id="001">
- <name>XY1</name>
- <age>22</age>
- </person>
- <person id="002">
- <name>XY2</name>
- <age>22</age>
- </person>
- </people>
- public class PersonService
- {
- public List getPeople(InputStream xml) throws Exception
- {
- List lst = null;
- Person person = null;
- // 获得pull解析器工厂
- XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();
- //获取XmlPullParser的实例
- XmlPullParser pullParser = pullParserFactory.newPullParser();
- // 设置需要解析的XML数据
- pullParser.setInput(xml, "UTF-8");
- // 取得事件
- int event = pullParser.getEventType();
- // 若为解析到末尾
- while (event != XmlPullParser.END_DOCUMENT) // 文档结束
- {
- // 节点名称
- String nodeName = pullParser.getName();
- switch (event)
- {
- case XmlPullParser.START_DOCUMENT: // 文档开始
- lst = new ArrayList();
- break;
- case XmlPullParser.START_TAG: // 标签开始
- if ("person".equals(nodeName))
- {
- String id = pullParser.getAttributeValue(0);
- person = new Person();
- person.setId(id);
- }
- if ("name".equals(nodeName))
- {
- String name = pullParser.nextText();
- person.setName(name);
- }
- if ("age".equals(nodeName))
- {
- int age = Integer.valueOf(pullParser.nextText());
- person.setAge(age);
- }
- break;
- case XmlPullParser.END_TAG: // 标签结束
- if ("person".equals(nodeName))
- {
- lst.add(person);
- person = null;
- }
- break;
- }
- event = pullParser.next(); // 下一个标签
- }
- return lst;
- }
- }