<?xml version=‘1.0‘ encoding=‘utf-8‘ standalone=‘yes‘ ?>
<weather>
<city>
<name>上海</name>
<temp>5°</temp>
<pm>80</pm>
</city>
<city>
<name>北京</name>
<temp>-5°</temp>
<pm>800</pm>
</city>
<city>
<name>西安</name>
<temp>12°</temp>
<pm>60</pm>
</city>
</weather>
package com.test.pullparser;
public class CityBean {
private String name;
private String temp;
private String pm;
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 getPm() {
return pm;
}
public void setPm(String pm) {
this.pm = pm;
}
}
package com.test.pullparser;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;
public class MainActivity extends Activity {
List<CityBean> cityList = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v){
//拿到xml文件
//获取src文件夹下的文件
InputStream inputStream = getClassLoader().getResourceAsStream("weather.xml");
//使用pull解析器解析文件
//获取解析器对象
XmlPullParser xp = Xml.newPullParser();
//初始化
try {
CityBean city = null;
xp.setInput(inputStream,"utf-8");
/*获取当前节点的事件类型,通过事件类型的判断,可以知道当前节点是
什么节点,从而确定将要执行的操作
int START_DOCUMENT = 0;//解析到了头节点
int END_DOCUMENT = 1;//解析结束
int START_TAG = 2;//解析到开始标签
int END_TAG = 3;//解析到结束标签
int TEXT = 4;
int CDSECT = 5;//CData区
int ENTITY_REF = 6;
int IGNORABLE_WHITESPACE = 7;
int PROCESSING_INSTRUCTION = 8;
int COMMENT = 9;
int DOCDECL = 10;
*/
int type = xp.getEventType();
while(type != XmlPullParser.END_DOCUMENT){
//获取下一个节点,并返回该节点的事件类型
//根据节点的事件类型,要做不同的操作
switch (type) {
case XmlPullParser.START_TAG:
//获取当前节点的名字
if("weather".equals(xp.getName())){
//创建cityJavabean对象,用于存放city集合
cityList = new ArrayList<CityBean>();
}else if("city".equals(xp.getName())){
//创建cityJavabean对象
city = new CityBean();
}else if("name".equals(xp.getName())){
try {
String name = xp.nextText();
city.setName(name);
} catch (IOException e) {
e.printStackTrace();
}
}
else if("temp".equals(xp.getName())){
try {
String temp = xp.nextText();
city.setTemp(temp);
} catch (IOException e) {
e.printStackTrace();
}
}
else if("pm".equals(xp.getName())){
try {
String pm = xp.nextText();
city.setPm(pm);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case XmlPullParser.END_TAG:
if("city".equals(xp.getName())){
//把city javabean放入集合中
cityList.add(city);
}
break;
default:
break;
}
}
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
原文:http://blog.csdn.net/ning_xian_hong/article/details/46238433