--> pull解析器是android内置的解析器,解析原理与sax类似
--> xml文件student.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- 有三个学生:姓名、年龄、性别。把这三个学生的信息用xml表示出来 -->
<students>
<student name="zhangsan">
<age>18</age>
<sex>男</sex>
</student>
<student name="lisi">
<age>22</age>
<sex>女</sex>
</student>
<student name="wangwu">
<age>20</age>
<sex>男</sex>
</student>
</students>
--> Student 类:
package com.dragon.java.pullparse; public class Student {
private String name;
private int age;
private String sex; public Student() {
super();
} public Student(String name, int age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
} 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 getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} @Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", sex=" + sex + "]";
} }
Student
--> Test 测试类:
package com.dragon.java.pullparse; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
import static org.xmlpull.v1.XmlPullParser.END_TAG;
import static org.xmlpull.v1.XmlPullParser.START_TAG;
import static org.xmlpull.v1.XmlPullParser.TEXT; import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory; /*
* pull解析器
*/
public class Test {
public static void main(String[] args) throws XmlPullParserException,
IOException {
List<Student> list = null;
Student student = null;
// 1、获取一个XmlPullParser解析器
XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); // 调用解析器工厂的静态方法,创建一个解析器工厂
XmlPullParser parser = factory.newPullParser(); // 创建一个pull解析器
parser.setInput(new FileReader(
"D:/workspace/08-25/src/com/dragon/java/xml/students.xml")); // 设置一个输入流,告诉要解析的xml数据的来源
int event = parser.getEventType(); // 获取当前事件的类型
while (event != END_DOCUMENT) { // 当碰到文档结束的时候,结束循环
switch (event) {
case START_TAG:
String tag = parser.getName();
if (tag.equals("students")) {
list = new ArrayList<>();
} else if (tag.equals("student")) {
student = new Student();
student.setName(parser.getAttributeValue(null, "name")); // 参数1:是命名空间,如果命名空间,则传入null。参数2:属性的名字
list.add(student);
} else if (tag.equals("age")) {
student.setAge(Integer.parseInt(parser.nextText())); // 获取当前事件后面的text事件,text的值
} else if (tag.equals("sex")) {
student.setSex(parser.nextText());
}
break;
case END_TAG:
break;
case TEXT:
break;
default:
break;
}
event = parser.next();
}
for (Student student2 : list) {
System.out.println(student2);
}
}
}
--> 也是蛮麻烦的...