1 public List<Person> DecodeXml(String filename) throws XmlPullParserException
2 {
3 // 获取当前程序的asset对象
4 AssetManager am = context.getAssets();
5
6 List<Person> pList = new ArrayList<Person>();
7
8 try {
9
10 //打开asset中文件为filename的文件,并以InputStream流的数据返回
11 InputStream is = am.open(filename);
12
13 //new一个XmlPullParser对象实例
14 XmlPullParser xpp = Xml.newPullParser();
15 //用要解析的Xml文件流初始化new出来的XmlPullParser实例对象
16 xpp.setInput(is, "utf-8");
17
18 //开始解析
19 int type = xpp.getEventType();//得到xpp的当前事件类型
20 Person person = null;
21
22 while(type!= XmlPullParser.END_DOCUMENT){//当前节点不等于xml文档的末尾时进行
23
24 if(type == XmlPullParser.START_TAG)//当当前标签是一个信息节点的开始标签时,这里也就是一个person节点的开始时
25 {
26 //创建一个Person对象用来存储 数据
27 person = new Person();
28
29 if("person".equals(xpp.getName())){//当前类型是是<person>标签是
30
31 person.setId(Integer.parseInt(xpp.getAttributeValue(0)));//获取当前标签的第一个属性
32 }
33 else if("name".equals(xpp.getName())){
34
35 person.setName(xpp.nextText());//获取当前标签对中的内容如<name>aaa</name>得到的内容是aaa
36 }
37 else if("age".equals(xpp.getName())){
38
39 person.setAge(Integer.parseInt(xpp.nextText()));
40 }
41 else if("sex".equals(xpp.getName())){
42
43 person.setSex(xpp.nextText());
44 }
45 }
46
47 if(type == XmlPullParser.END_TAG){//当前类型是一个信息节点的末尾标签时,这里也就是</pserson>
48
49 pList.add(person);
50 }
51
52 //跳到下一个标签
53 type = xpp.next();
54 }
55
56 return pList;
57
58 } catch (IOException e) {
59
60 e.printStackTrace();
61 return null;
62 }
63
64 }