Android XML解析之Pull
Pull解析XML文档;
首先建一个android项目,在cn.class3g.service里建一个名为person_list,xml:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="111">
<name>Tom</name>
<age>20</age>
</person>
<person id="222">
<name>Mary</name>
<age>17</age>
</person>
</persons>
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="111">
<name>Tom</name>
<age>20</age>
</person>
<person id="222">
<name>Mary</name>
<age>17</age>
</person>
</persons>
在cn.class3g.domain包下封装javabean,person:
package cn.class3g.domain;
public class Person {
private int id;
private String name;
private int age;
public Person() {
}
public Person(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
package cn.class3g.domain;
public class Person {
private int id;
private String name;
private int age;
public Person() {
}
public Person(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
在service包下创建PersonHandler类
<pre name="code" class="html">package cn.class3g.service;
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;
import cn.class3g.domain.Person;
public class PullPersonService {
public static List<Person> getPersonList(InputStream inStream)
throws Exception {
List<Person> personList = null;
//拿到XmlPullParser解析器
XmlPullParser parser = Xml.newPullParser();
//统一编码
parser.setInput(inStream, "utf-8");
int eventType = parser.getEventType();
//创建一个person对象
Person person = null;
//开始解析
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
personList = new ArrayList<Person>();
break;
case XmlPullParser.START_TAG:
// 判断当前元素名是否为person
if ("person".equals(parser.getName())) {
person = new Person();
person.setId(Integer.valueOf(parser.getAttributeValue(0)));
} else if ("name".equals(parser.getName())) {
person.setName(parser.nextText());
} else if ("age
补充:移动开发 , Android ,