Android 解析XML文件 XmlPullParser 方法

来源:互联网 发布:swoole php 编辑:程序博客网 时间:2024/06/05 22:59

解析文件

<?xml version="1.0" encoding="utf-8"?><infos><city id="1"><temp>20度/30度</temp><weather>5月20日 多云转阴</weather><wind>南风3-4级</wind><name>上海</name><pm>200</pm></city><city id="2"><temp>26度/30度</temp><weather>5月20日 多云转阴</weather><wind>南风7-8级</wind><name>北京</name><pm>800</pm></city><city id="3"><temp>10度/20度</temp><weather>5月20日 多云转阴</weather><wind>南风2-3级</wind><name>哈尔滨</name><pm>600</pm></city></infos>


生成实体类,省略GET\SET

public class WeatherInfo {private int id;private String name;private String wind;private String weather;private String temp;private String pm;@Overridepublic String toString() {return " [城市id=" + id + ", 名称=" + name + ", 风力=" + wind+ ", 天气状况=" + weather + ", 温度=" + temp + ", pm2.5=" + pm+ "]";}


解析方法

package com.asus.service;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import org.xmlpull.v1.XmlPullParser;import android.util.Xml;import com.asus.entity.WeatherInfo;public class WeatherInfoService {public static List<WeatherInfo> getWeatherInfos(InputStream is) throws Exception{XmlPullParser parser = Xml.newPullParser();//初始化解析器parser.setInput(is, "UTF-8");List<WeatherInfo> weatherInfos = null;WeatherInfo weatherInfo = null;int type = parser.getEventType();while(type != XmlPullParser.END_DOCUMENT){switch (type) {case XmlPullParser.START_TAG:if("infos".equals(parser.getName()))//解析到全局标签weatherInfos = new ArrayList<WeatherInfo>();else if("city".equals(parser.getName())){weatherInfo = new WeatherInfo();String idString = parser.getAttributeValue(0);weatherInfo.setId(Integer.parseInt(idString));} else if("temp".equals(parser.getName())){String temp = parser.nextText();weatherInfo.setTemp(temp);}else if("weather".equals(parser.getName())){String weather = parser.nextText();weatherInfo.setWeather(weather);}else if("wind".equals(parser.getName())){String wind = parser.nextText();weatherInfo.setWind(wind);}else if("name".equals(parser.getName())){String name = parser.nextText();weatherInfo.setName(name);}else if("pm".equals(parser.getName())){String pm = parser.nextText();weatherInfo.setPm(pm);}break;case XmlPullParser.END_TAG:if("city".equals(parser.getName())){//一个城市的信息已经处理完毕weatherInfos.add(weatherInfo);weatherInfo = null;}break;}type = parser.next();}return weatherInfos;}}


MainActivity 中使用一个TextView 控件显示

TextView tView = (TextView) findViewById(R.id.tv);try {List<WeatherInfo> infos = WeatherInfoService.getWeatherInfos(MainActivity.class.getClassLoader().getResourceAsStream("weather.xml"));StringBuffer sb = new StringBuffer();for(WeatherInfo info : infos){String str = info.toString();sb.append(str);sb.append("\n");}tView.setText(sb.toString());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show();}

 

至此完成.

原创粉丝点击