Android之xml解析

利用类下载器解析Xml文件
要解析的xml文件
<?xml version="1.0" encoding="utf-8"?>
<info>
<city name="北京">
<temp>18度</temp>
<sun>晴</sun>
</city>
<city name="杭州">
<temp>26度</temp>
<sun>雨夹雪</sun>
</city>

<city name="武汉">
<temp>46°C</temp>
<sun>下雪</sun>
</city>
</info>
首先建一个Info实体类,其属性与Info.xml节点对应
public class Info {
private String city;
private String sun;
private String temp;



public String getSun() {
return sun;
}

@Override
public String toString() {
return "Info [getSun()=" + getSun() + ", getTemp()=" + getTemp()
+ ", getCity()=" + getCity() + "]";
}

public void setSun(String sun) {
this.sun = sun;
}


public String getTemp() {
return temp;
}

public void setTemp(String temp) {
this.temp = temp;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}
}
创建一个解析文件的方法供调用
public static List<Info> GetInfoList(InputStream inputStream) throws Exception{
List<Info> listInfo =null;
Info info =null;
XmlPullParser xmlParser =Xml.newPullParser();
xmlParser.setInput(inputStream,"utf-8");
int type =xmlParser.getEventType();//获取解析器解析的事件类型
while(type!=xmlParser.END_DOCUMENT){
switch (type) {
case XmlPullParser.START_TAG://标签或者节点开始时候的事件
if("info".equals(xmlParser.getName())){
//初始化 天气信息集合
listInfo = new ArrayList<Info>();
}
else if("city".equals(xmlParser.getName())){
info = new Info();
String city = xmlParser.getAttributeValue(0);
info.setCity(city);
}
else if("temp".equals(xmlParser.getName())){
String temp = xmlParser.nextText();
info.setTemp(temp);
}
else if("sun".equals(xmlParser.getName())){
String sun = xmlParser.nextText();
info.setSun(sun);
}
break;
case XmlPullParser.END_TAG:
if("city".equals(xmlParser.getName())){ //发现已经解析完毕一个城市信息
listInfo.add(info);
info = null;
}
break;
}
type = xmlParser.next();//让解析器 解析下一个节点tag
}
return listInfo;
}
最后,调用这个方法解析文件并返回
TextView txtViewWeather=(TextView) findViewById(R.id.txtViewWeather);
InputStream inputStream =getClassLoader().getResourceAsStream("info.xml");
try {
List<Info> listInfo=WeatherService.GetInfoList(inputStream);
StringBuilder sb=new StringBuilder();
for(Info item:listInfo){
sb.append(item.toString());
}
txtViewWeather.setText(sb.toString());
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
Toast.makeText(this, "解析异常啦,哈哈哈!", Toast.LENGTH_LONG).show();
}

原文地址:https://www.cnblogs.com/huangzhen22/p/4191762.html