0%

XMLParaser解析xml

1、首先附上要解析的xml数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8"?>
<weather>
<city>
<name>西安</name>
<temp>23</temp>
<pm25>40</pm25>
</city>
<city>
<name>郑州</name>
<temp>26</temp>
<pm25>100</pm25>
</city>
<city>
<name>镇巴</name>
<temp>28</temp>
<pm25>800</pm25>
</city>
</weather>

2、根据xml的结果设计JavaBean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package domain;

public class City {
private String name;
private String temp;
private String pm25;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getPm25() {
return pm25;
}
public void setPm25(String pm25) {
this.pm25 = pm25;
}
@Override
public String toString() {
return "City [name=" + name + ", temp=" + temp + ", pm25=" + pm25 + "]";
}

}

3、点击按钮开始解析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;
import domain.City;

public class MainActivity extends Activity {
List<City> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}

public void click(View v){
//获取天气xml文件
InputStream is = getClassLoader().getResourceAsStream("weather.xml");

//获取xml解析器
XmlPullParser parser = Xml.newPullParser();

try{
//初始化
parser.setInput(is, "UTF-8");

//获取当前节点的事件类型
int type = parser.getEventType();

City city = null;
//不到文档结束就一直解析
while(type != XmlPullParser.END_DOCUMENT){
switch (type) {
case XmlPullParser.START_TAG:
//获取当前节点的名称
if("weather".equals(parser.getName())){
list = new ArrayList<City>();
}else if("city".equals(parser.getName())){
city = new City();
}else if("name".equals(parser.getName())){
//获取下一个节点的文本,而且把指针移动到当前节点的结束节点
city.setName(parser.nextText());
}else if("temp".equals(parser.getName())){
city.setTemp(parser.nextText());
}else if("pm25".equals(parser.getName())){
city.setPm25(parser.nextText());
}
break;
case XmlPullParser.END_TAG:
if("city".equals(parser.getName())){
list.add(city);
}
break;
}
type = parser.next();
}
}catch(Exception e){
e.printStackTrace();
}

//输出数据
for (City city : list) {
System.out.println(city.toString());
}
}
}

mark

  • 本文作者: Tim
  • 本文链接: https://zouchanglin.cn/3983747791.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!