XMLParaser解析xml

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

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

2、根据xml的结果设计JavaBean

 1package domain;
 2
 3public class City {
 4	private String name;
 5	private String temp;
 6	private String pm25;
 7	public String getName() {
 8		return name;
 9	}
10	public void setName(String name) {
11		this.name = name;
12	}
13	public String getTemp() {
14		return temp;
15	}
16	public void setTemp(String temp) {
17		this.temp = temp;
18	}
19	public String getPm25() {
20		return pm25;
21	}
22	public void setPm25(String pm25) {
23		this.pm25 = pm25;
24	}
25	@Override
26	public String toString() {
27		return "City [name=" + name + ", temp=" + temp + ", pm25=" + pm25 + "]";
28	}
29	
30}
31

3、点击按钮开始解析

 1import java.io.InputStream;
 2import java.util.ArrayList;
 3import java.util.List;
 4
 5import org.xmlpull.v1.XmlPullParser;
 6
 7import android.app.Activity;
 8import android.os.Bundle;
 9import android.util.Xml;
10import android.view.View;
11import domain.City;
12
13public class MainActivity extends Activity {
14	List<City> list;
15    @Override
16    protected void onCreate(Bundle savedInstanceState) {
17        super.onCreate(savedInstanceState);
18        setContentView(R.layout.activity_main);
19        
20    }
21    
22    public void click(View v){
23    	//获取天气xml文件
24    	InputStream is = getClassLoader().getResourceAsStream("weather.xml");
25    	
26    	//获取xml解析器
27    	XmlPullParser parser = Xml.newPullParser();
28    	
29    	try{
30    		//初始化
31    		parser.setInput(is, "UTF-8");
32    		
33    		//获取当前节点的事件类型
34    		int type = parser.getEventType();
35    		
36    		City city = null;
37    		//不到文档结束就一直解析
38    		while(type != XmlPullParser.END_DOCUMENT){
39    			switch (type) {
40				case XmlPullParser.START_TAG:
41					//获取当前节点的名称
42					if("weather".equals(parser.getName())){
43						list = new ArrayList<City>();
44					}else if("city".equals(parser.getName())){
45						city = new City();
46					}else if("name".equals(parser.getName())){
47						//获取下一个节点的文本,而且把指针移动到当前节点的结束节点
48						city.setName(parser.nextText());
49					}else if("temp".equals(parser.getName())){
50						city.setTemp(parser.nextText());
51					}else if("pm25".equals(parser.getName())){
52						city.setPm25(parser.nextText());
53					}
54					break;
55				case XmlPullParser.END_TAG:
56					if("city".equals(parser.getName())){
57						list.add(city);
58					}
59					break;
60				}
61    			type = parser.next();    			
62    		}
63    	}catch(Exception e){
64    		e.printStackTrace();
65    	}
66    	
67    	//输出数据
68    	for (City city : list) {
69			System.out.println(city.toString());
70		}
71    }
72}

mark