android解析xml格式数据

来源:互联网 发布:雨露计划软件下载 编辑:程序博客网 时间:2024/05/19 18:11

废话不多说,直接开工

我们解析如下的xml文件中的内容


解析的代码如下

package com.example.readxml825.service;import java.io.InputStream;import java.util.ArrayList;import java.util.List;import org.xmlpull.v1.XmlPullParser;import android.util.Xml;import com.example.readxml825.domain.WeatherInfos;public class WeatherService {public static List<WeatherInfos> getWeatherInfos(InputStream is)throws Exception{//创建xml解析器XmlPullParser parser = Xml.newPullParser();//初始化解析器parser.setInput(is, "utf-8");//得到数据类型List<WeatherInfos> weatherInfos=null;WeatherInfos weatherinfo=null;int type=parser.getEventType();//循环解析xml文件while(type!=XmlPullParser.END_DOCUMENT){switch (type) {//处理开始标签case XmlPullParser.START_TAG:if("infos".equals(parser.getName())){weatherInfos=new ArrayList<WeatherInfos>();}else if("city".equals(parser.getName())){weatherinfo = new WeatherInfos();String idStr=parser.getAttributeValue(0);weatherinfo.setId(Integer.parseInt(idStr));}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;}default:break;}type=parser.next();}return weatherInfos;}}
其中的weatherinfos类内容如下

package com.example.readxml825.domain;public class WeatherInfos {private int id;private String name;private String temp;private String wind;private String weather;private String pm;@Overridepublic String toString() {return "WeatherInfos [id=" + id + ", name=" + name + ", temp=" + temp+ ", wind=" + wind + ", weather=" + weather + ", pm=" + pm+ "]";}public int getId() {return id;}public void setId(int id) {this.id = id;}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 getWind() {return wind;}public void setWind(String wind) {this.wind = wind;}public String getWeather() {return weather;}public void setWeather(String weather) {this.weather = weather;}public String getPm() {return pm;}public void setPm(String pm) {this.pm = pm;}}

函数调用

List<WeatherInfos> weatherInfos=WeatherService.getWeatherInfos(MainActivity.class.getClassLoader().getResourceAsStream("weather.xml"));StringBuffer sb = new StringBuffer();for(WeatherInfos info:weatherInfos){String str=info.toString();sb.append(str);sb.append("\n");}System.out.println(sb);//sb字符转中的内容就是解析好的具体数据



0 0
原创粉丝点击