1、文件目录
2、weather.xml
3、解析xml文件源码
(1)channel.java文件
public class Channel {
private String id;
private String city;
private String temp;
private String wind;
private String pm250;
public String getId(String id){
return id;
}
public void setId(String id){
this.id=id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getPm250() {
return pm250;
}
public void setPm250(String pm250) {
this.pm250 = pm250;
}
@Override
public String toString() {
return "Channel [id=" + id + ", city=" + city + ", temp=" + temp
+ ", wind=" + wind + ", pm250=" + pm250 + "]";
}
2、WeahterParser.java
public class WeatherParser {
public static List<Channel> parserXml(InputStream in) throws Exception {
//[0]声明集合对象
List<Channel> weatherLists = null;
Channel channel = null;
//[1]获取XmlPullParser 解析的实例
XmlPullParser parser = Xml.newPullParser();
//[2]设置XmlPullParser 的参数
parser.setInput(in, "utf-8");
//[3]获取事件类型
int type = parser.getEventType();
while(type!= XmlPullParser.END_DOCUMENT){
switch (type) {
case XmlPullParser.START_TAG: //解析开始标签
//[4]具体判断一下 解析到是哪个开始标志
if ("weather".equals(parser.getName())) {
//[5]创建一个集合对象
weatherLists = new ArrayList<Channel>();
}else if("channel".equals(parser.getName())){
//[6]创建Channel对象
channel = new Channel();
//[7]获取id值
String id = parser.getAttributeValue(0);
channel.setId(id);
}else if("city".equals(parser.getName())){
//[8]获取city的数据
String city = parser.nextText();
channel.setCity(city);
}else if("temp".equals(parser.getName())){
//[8]获取city的数据
String temp = parser.nextText();
channel.setTemp(temp);
}else if("wind".equals(parser.getName())){
//[8]获取city的数据
String wind = parser.nextText();
channel.setWind(wind);
}else if("pm250".equals(parser.getName())){
//[8]获取city的数据
String pm250 = parser.nextText();
channel.setPm250(pm250);
}
break;
case XmlPullParser.END_TAG: //解析结束标志
//判断要解析的结束标签
if("channel".equals(parser.getName()){
//把javabean对象存到集合中
weatherLists.add(channel);
}
break;
}
//不停的向下解析
type = parser.next();
}
return weatherLists;
}
(3)MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView=(TextView)findViewById(R.id.weather);
try {
//[1]显示天气信息
TextView tv_weather = (TextView) findViewById(R.id.weather);
//[1.1]获取资产的管理者 通过上下文
InputStream inputStream = getAssets().open("weather.xml");
//[2]调用我们定义的解析xml业务方法
List<Channel> weatherlists = WeatherParser.parserXml(inputStream);
StringBuffer sb = new StringBuffer();
for (Channel channel : weatherlists) {
sb.append(channel.toString());
}
//[3]把数据展示到textviwe上
tv_weather.setText(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}