XML解析的初步学习
weatherService页面,解析Xml
<infos>
<city id="sh">
<name>上海</name>
<temp>20/30</temp>
</city>
<city id="xm">
<name>厦门</name>
<temp>25/30</temp>
</city>
<city id="fz">
<name>福州</name>
<temp>5/10</temp>
</city>
</infos>
public class weatherService {
public static List<weatherinfo>getInfoFromXMl(InputStream is)throws Exception{
XmlPullParser parser = Xml.newPullParser();//得到pull解析器
parser.setInput(is,"utf-8");//初始化解析器,第一个参数为xml数据
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<>();
}else if ("city".equals(parser.getName())){
weatherinfo=new weatherinfo();
weatherinfo.setId(parser.getAttributeValue(0));
}else if ("name".equals(parser.getName())){
weatherinfo.setName(parser.nextText());
}else if ("temp".equals(parser.getName())){
weatherinfo.setTemp(parser.nextText());
}
break;
case XmlPullParser.END_TAG://节点的结束标签
if ("city".equals(parser.getName())) {
weatherinfos.add(weatherinfo);
}
break;
}
type=parser.next();
}
return weatherinfos;
}
}
MainActivity页面,对weatherService的获取
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
InputStream is= this.getResources().openRawResource(R.raw.weather);
try {
List<weatherinfo>infos= weatherService.getInfoFromXMl(is);
weatherinfoMap=new HashMap<>();
for (weatherinfo info:infos) {
weatherinfoMap.put(info.getId(),info);
}
} catch (Exception e) {
e.printStackTrace();
}
getMap("xm");
}