<?xml version="1.0" encoding="UTF-8" ?>
<students>
<student class="j2307">
<name>张三丰</name>
<sex>男</sex>
<age>25</age>
</student>
<student class="j2307">
<name>周芷若</name>
<sex>女</sex>
<age>23</age>
</student>
</students>
//解析xml文件 pull 方式
public void parseXML(View view){
try {
//获取xm文件流 assets文件目录下
InputStream inputStream= this.getAssets().open("student.xml");
//定义一个xml解析的pull对象
XmlPullParser xmlPullParser = Xml.newPullParser();
//把文件交给解析器
xmlPullParser.setInput(inputStream,"UTF-8");
//获取解析一行的事件
int event = xmlPullParser.getEventType();
List<Student> students =null;
Student student=null;
//控制解析器一行一行 解析xml文件 文档结束
while(event != XmlPullParser.END_DOCUMENT){
switch (event){
//文档开始
case XmlPullParser.START_DOCUMENT:
//开始解析文档 定义一个集合存储数据
students = new ArrayList<>();
break;
//打开标签
case XmlPullParser.START_TAG:
if(xmlPullParser.getName().equals("student")){
//每次解析一项就创建一个对象
student = new Student();
student.clazz = xmlPullParser.getAttributeValue(0);
}else if(xmlPullParser.getName().equals("name")){
student.name = xmlPullParser.nextText();
}else if(xmlPullParser.getName().equals("sex")){
student.sex = xmlPullParser.nextText();
}else if(xmlPullParser.getName().equals("age")){
student.age = xmlPullParser.nextText();
}
break;
//文档结束标签
case XmlPullParser.END_TAG:
if(xmlPullParser.getName().equals("student")){
//添加到集合
students.add(student);
}
break;
}
//解析下一行
event = xmlPullParser.next();
}
textView.setText(students.toString());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplication(),"解析数据失败!",Toast.LENGTH_SHORT).show();
}
}
--
[Student{clazz='j2307',name='张三丰',sex='男',age='25'},Student{clazz='j2307'',name='周芷若',sex='女',age='23'}]