xmlpull解析也是跟sax解析一样,都是边解析边释放,所以不会像dom解析那样出现出现溢出。
他的实现代码如下:
package itcast.cn;
import java.io.FileInputStream;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
//把两个person封装到集合里面
//则需要有两个对象,然后把数据放在对象里面,之后把对象放在集合里面
public class Pull {
public static void main(String[] args) throws Exception {
//必须要导入家暴--由于是第三方的,所以要导入
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser pullParser = factory.newPullParser();
//解析文件
pullParser.setInput(new FileInputStream("person.xml"), "utf-8");
//获取事件类型
int type=pullParser.getEventType();
//循环移动解析器
Person person=null;
ArrayList<Person> persons =null;
while(type!=XmlPullParser.END_DOCUMENT){
switch(type){
case XmlPullParser.START_TAG:
if (pullParser.getName().equals("persons")) {
persons = new ArrayList<Person>();
}else if (pullParser.getName().equals("person")) {
person=new Person();
String id = pullParser.getAttributeValue(0);
person.setId(id);
}else if (pullParser.getName().equals("name")) {
//拿到下一个的值
String name= pullParser.nextText();
person.setName(name);
}else if (pullParser.getName().equals("age")) {
String age= pullParser.nextText();
//由于得到的是String类型,所以需要将这个String类型的转换成int
person.setAge(Integer.parseInt(age));
}
break;
case XmlPullParser.END_TAG:
if (pullParser.getName().equals("person")) {
persons.add(person);
}
break;
default:
break;
}
type=pullParser.next();
}
System.out.println(persons);
}
}
Person对象:
package itcast.cn;
public class Person {
private String name;
private int age;
private String id;
public String getId() {
return id;
}
public void setId(String 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;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", id=" + id + "]";
}
public Person(String id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
}