xml解析之Pull
为了学习Pull解析xml,可以简单的做个小Demo
-
第一步:以字符串的形式创建出xml。
String str = "<?xml version="1.0" encoding="UTF-8"?>\n" +
"<persons>\n" +
" <person id="1">\n" +
" <name>小罗</name>\n" +
" <age>21</age>\n" +
" </person>\n" +
" <person id="2">\n" +
" <name>android</name>\n" +
" <age>15</age>\n" +
" </person>\n" +
"</persons>"; -
第二步:根据xml文件封装实体类:
public class Person implements Serializable {
int id;
String name;
int age;
public void setAge(int age) {
this.age = age;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
@Override public String toString() {
return "Person{" +
"age=" + age +
", id=" + id +
", name='" + name + ''' + '}';
}
} -
第三步:创建解析方法:
public List<Person> PullParseXml(InputStream inputStream) throws XmlPullParserException, IOException {
List<Person> persons = new ArrayList<>();
Person person = null;
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(inputStream, "utf-8");
int eventType = xmlPullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
// 解析到文档开始的时候
case XmlPullParser.START_DOCUMENT:
persons = new ArrayList<Person>();
break;
// 解析到xml标签的时候
case XmlPullParser.START_TAG:
if ("person".equals(xmlPullParser.getName())) {
person = new Person();
// 得到person元素的第一个属性,也就是ID
person.setId(Integer.parseInt(xmlPullParser.getAttributeValue(0)));
} else if ("name".equals(xmlPullParser.getName())) {
// 如果是name元素,则通过nextText()方法得到元素的值
person.setName(xmlPullParser.nextText());
} else if ("age".equals(xmlPullParser.getName())) {
person.setAge(Integer.parseInt(xmlPullParser.nextText()));
}
break;
// 解析到xml标签结束的时候
case XmlPullParser.END_TAG:
if ("person".equals(xmlPullParser.getName())) {
persons.add(person);
person = null;
}
break;
}
// 通过next()方法触发下一个事件
eventType = xmlPullParser.next();
}
return persons;
} -
第四步:调用解析方法:
byte[] bytes = str.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
try {
persons = PullParseXml(inputStream);
Log.d("TAG", "size = " + persons.size());
Log.d("TAG", persons.get(0).toString());
Log.d("TAG", persons.get(1).toString());
} catch (Exception e) {
e.printStackTrace();
} -
第五步:运行程序,你会得到如下Log: