android解析xml和json文件
weather1.xml
<?xml version="1.0" encoding="utf-8"?>
<infos>
<city id="sh">
<temp>20℃/30℃</temp>
<weather>晴天多云</weather>
<name>上海</name>
<pm>80</pm>
<wind>1级</wind>
</city>
<city id="bj">
<temp>26℃/32℃</temp>
<weather>晴天</weather>
<name>北京</name>
<pm>98</pm>
<wind>3级</wind>
</city>
</infos>
weather2.json
[
{"temp":"20℃/30℃","weather":"晴转多云","name":"上海","pm":"80","wind":"1级"},
{"temp":"15℃/24℃","weather":"晴","name":"北京","pm":"98","wind":"3级"}
]
weatherService.java(解析xml文件和json文件的工具类)
package com.example.myapplicationsax;
import android.util.Xml;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class weatherService {
//解析xml文件返回天气信息集合
public static List<weatherInfo> getInfoFromXml(InputStream is) throws XmlPullParserException, IOException {
//获取解析器
XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
XmlPullParser parser=factory.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_DOCUMENT:
//解析infos根节点
//实例化集合对象
weatherInfos=new ArrayList<weatherInfo>();
break;
case XmlPullParser.START_TAG:
if("city".equals(parser.getName())){
weatherinfo=new weatherInfo();
String idStr=parser.getAttributeValue(0);
weatherinfo.setId(idStr);
}else if ("temp".equals(parser.getName())){
//parser.nextText()获取节点内容
weatherinfo.setTemp(parser.nextText());
}else if ("weather".equals(parser.getName())){
//parser.nextText()获取节点内容
weatherinfo.setWeather(parser.nextText());
}else if ("name".equals(parser.getName())){
//parser.nextText()获取节点内容
weatherinfo.setName(parser.nextText());
}else if ("pm".equals(parser.getName())){
//parser.nextText()获取节点内容
weatherinfo.setPm(parser.nextText());
}else if ("wind".equals(parser.getName())){
//parser.nextText()获取节点内容
weatherinfo.setWind(parser.nextText());
}
break;