这里介绍下在Android中极力推荐的xmlpull方式解析xml。xmlpull不仅仅可以使用在Android上,同样也适用于javase,但在javase环境下,你需要自己去获取xmlpull所依赖的类库。
下面是我自己写的一个例子。
1.XML源数据
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="1">
<name>张三</name>
<address>湖北武汉</address>
</person>
<person id="2">
<name>李四</name>
<address>湖北宜昌</address>
</person>
</persons>
2.解析输入流的方法
public List<Person> parseXml(InputStream inputStream)
throws XmlPullParserException, IOException {
List<Person> personList = Collections.EMPTY_LIST;
Person person = null;
XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory
.newInstance();
XmlPullParser xmlPullParser = xmlPullParserFactory.newPullParser();
// 设置输入流
xmlPullParser.setInput(inputStream, "utf-8");
int eventCode = xmlPullParser.getEventType();
while (eventCode != XmlPullParser.END_DOCUMENT) {
String nodeName = xmlPullParser.getName();
switch (eventCode) {
case XmlPullParser.START_DOCUMENT:
personList = new ArrayList<Person>();
break;
case XmlPullParser.START_TAG:
if ("person".equals(nodeName)) {
person = new Person();
person.setId(Integer.parseInt(xmlPullParser
.getAttributeValue(0)));
}
if ("name".equals(nodeName)) {
person.setName(xmlPullParser.nextText());
}
if ("address".equals(nodeName)) {
person.setAddress(xmlPullParser.nextText());
}
break;
case XmlPullParser.END_TAG:
if ("person".equals(nodeName)) {
personList.add(person);
person = null;
}
break;
default:
break;
}
eventCode = xmlPullParser.next();
}
return personList;
}
3.测试方法
public static void main(String[] args) {
InputStream inputStream = XmlPullTest.class
.getResourceAsStream("persons.xml");
XmlPullTest xmlPullTest = new XmlPullTest();
try {
List<Person> personList = xmlPullTest.parseXml(inputStream);
System.out.println(personList);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
好了,以上就是我学习安卓的基于XMLPULL解析XML的相关方法。