android应用程序中xml文件的pull解析:
要解析的xml文件为:info.xml,放置于src下
<?xml version="1.0" encoding="utf-8"?> <info> <city name="北京"> <temp>28°C</temp> <wind>3~4级</wind> <sun>晴</sun> </city> <city name="天津"> <temp>26°C</temp> <wind>3~4级</wind> <sun>雷阵雨</sun> </city> <city name="石家庄"> <temp>46°C</temp> <wind>3~9级</wind> <sun>下雪</sun> </city> <city name="邯郸"> <temp>16°C</temp> <wind>1~4级</wind> <sun>雷</sun> </city> </info>project文件结构如图:
将xml文件中的信息创建为JavaBean对象:
public class Weather { private String city; private String temp; private String wind; private String sun; 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 getSun() { return sun; } public void setSun(String sun) { this.sun = sun; } @Override public String toString() { return "天气: " + city + ",温度=" + temp + ",风力=" + wind +","+ sun; } }WeatherService.java类文件用pull解析读取xml文件中的信息:
public class WeatherService { public static List<Weather> getWeatherInfo(InputStream is) throws Exception{ XmlPullParser parser=Xml.newPullParser(); parser.setInput(is,"utf-8"); //获取解析器解析的事件类型 int type=parser.getEventType(); List<Weather> weathers = null; Weather weather = null; while(type!=XmlPullParser.END_DOCUMENT){ switch(type){ //标签或者节点开始时候的节点 case XmlPullParser.START_TAG: if("info".equals(parser.getName())){ //初始化天气集合信息 weathers=new ArrayList<Weather>(); }else if("city".equals(parser.getName())){ weather=new Weather(); String cityName=parser.getAttributeValue(0); weather.setCity(cityName); }else if("temp".equals(parser.getName())){ String temp=parser.nextText(); weather.setTemp(temp); }else if("wind".equals(parser.getName())){ String wind=parser.nextText(); weather.setWind(wind); }else if("sun".equals(parser.getName())){ String sun=parser.nextText(); weather.setSun(sun); } break; //标签结束 case XmlPullParser.END_TAG: //发现已解析完一个城市信息 if("city".equals(parser.getName())){ weathers.add(weather); weather=null; } break; } //让解析器去解析下一个tag节点 type=parser.next(); } return weathers; } }在布局文件中设置一个TextViw用于显示从xml中读取的信息,MainActivity.java
public class MainActivity extends Activity { private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_main); tv=(TextView) findViewById(R.id.tv); InputStream in=getClassLoader().getResourceAsStream("info.xml"); //解析xml获取天气信息 try { List<Weather> weathers= WeatherService.getWeatherInfo(in); StringBuilder sb=new StringBuilder(); for(Weather weather:weathers){ sb.append(weather); sb.append("\n"); } tv.setText(sb.toString()); } catch (Exception e) { e.printStackTrace(); Toast.makeText(this,"解析天气信息失败",1).show(); } } }
最终实现的效果如图: