java 解析xml文档

时间:2022-10-14 05:45:06
 1 package com.zx;
2
3 import java.io.FileInputStream;
4 import java.io.IOException;
5 import java.util.ArrayList;
6 import java.util.List;
7
8 import org.json.JSONException;
9 import org.xmlpull.v1.XmlPullParser;
10 import org.xmlpull.v1.XmlPullParserException;
11 import org.xmlpull.v1.XmlPullParserFactory;
12
13
14
15 class MyDay17Xml {
16
17 public static void main(String []args) throws JSONException{
18
19 }
20
21 public static List<Person> PullParserXml() throws XmlPullParserException, IOException {
22 //数据定义
23 List<Person> list=null;
24 Person person=null;
25 //获得xmlpullparser对象
26 XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
27 XmlPullParser parser=factory.newPullParser();
28 //获取输入流
29 FileInputStream fis=new FileInputStream("person.xml");
30 //设置流和字符集
31 parser.setInput(fis,"utf-8");
32 //开始解析
33 int event=parser.getEventType();
34 while(event!=XmlPullParser.END_DOCUMENT){
35 switch (event){
36 /**
37 * 开始标记,通常进行相关集合或者对象的初始化
38
39 */
40 case XmlPullParser.START_DOCUMENT:
41 list=new ArrayList<Person>();
           break;
42 case XmlPullParser.START_TAG:
43 String tagName=parser.getName();
44 //得到属性标记通过getName
45 if("person".equals(tagName)){
46 person=new Person();
47 //获得标记后的属性值通过getAttributeName和getAttributeValue两个方法
48 for(int i=0;i<parser.getAttributeCount();i++){
49 String name=parser.getAttributeName(i);
50 String value=parser.getAttributeValue(i);
51 if("id".equals(name)){
52 person.setId(value);
53 }
54 }
55 }else if("name".equals(tagName)){
56 //得到属性标记之后的值,通过nextText方法
57 person.setName(parser.nextText());
58 }else if("age".equals(tagName)){
59 person.setAge(parser.nextText());
60 }
           break;
61 case XmlPullParser.END_TAG:
62 if("person".equals(parser.getName())){
63 list.add(person);
64 person=null;
65 }
          break;
66 }
        event=parser.next();
67 }
68 //解析结束,返回集合
69 return list;
70 }
71
72 }
73 class Person{
74 private String name,age,id;
75
76 public String getName() {
77 return name;
78 }
79
80 public void setName(String name) {
81 this.name = name;
82 }
83
84 public String getAge() {
85 return age;
86 }
87
88 public void setAge(String age) {
89 this.age = age;
90 }
91
92 public String getId() {
93 return id;
94 }
95
96 public void setId(String id) {
97 this.id = id;
98 }
99 }