xml解析(使用pull解析)

前端之家收集整理的这篇文章主要介绍了xml解析(使用pull解析)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.要解析的xml文件

<?xmlversion= "1.0" encoding= "utf-8" ?>
<infos>
<cityid= "1" >
<temp> 20 ℃/ 30 ℃</temp>
<weather> 5 号多云转阴</weather>
<wind>南风 3 - 4 级</wind>
<name>上海</name>
<pm> 200 </pm>
</city>
"2" >
℃</temp>
21 号多云转阴</weather>
6 7 级</wind>
<name>北京</name>
100 </pm>
</city>
"3" >
10 ℃</temp>
号多云转阴</weather>
<wind>北风 级</wind>
<name>长沙</name>
</pm>
</city>
</infos>

2.写一个实体类

package com.example.testpull;
public class WeatherInfo{
int id;
Stringname;
Stringwind;
Stringweather;
Stringtemp;
Stringpm;
@Override
public StringtoString(){
return "id=" +id+ ",name=" +name+ +wind+
+weather+ +temp+ +pm;
}
}
3.定义解析的方法

import java.io.IOException;
java.io.InputStream;
java.util.ArrayList;
java.util.List;
org.xmlpull.v1.XmlPullParser;
org.xmlpull.v1.XmlPullParserException;
android.util.Xml;
WeathearService{
static List<WeatherInfo>getWeatherInfos(InputStreamis)
throws XmlPullParserException,IOException{
XmlPullParserparser=Xml.newPullParser();
List<WeatherInfo>weatherInfos= null ;
WeatherInfoweatherInfo= ;
//初始化解析器
parser.setInput(is, );
type=parser.getEventType(); //得到事件类型
@H_403_311@while (type!=XmlPullParser.END_DOCUMENT){
switch (type){
case XmlPullParser.START_TAG:
if ( "infos" .equals(parser.getName())){
weatherInfos= new ArrayList<WeatherInfo>();
} else "city" .equals(parser.getName())){
weatherInfo= WeatherInfo();
StringidStr=parser.getAttributeValue( 0 );
weatherInfo.id=Integer.parseInt(idStr);
"temp" .equals(parser.getName())){
Stringtemp=parser.nextText();
weatherInfo.temp=temp;
"weather" .equals(parser.getName())){
Stringweather=parser.nextText();
weatherInfo.weather=weather;
"wind" .equals(parser.getName())){
Stringwind=parser.nextText();
weatherInfo.wind=wind;
"name" .equals(parser.getName())){
@H_579_404@Stringname=parser.nextText();
weatherInfo.name=name;
"pm" .equals(parser.getName())){
Stringpm=parser.nextText();
weatherInfo.pm=pm;
}
break ;
XmlPullParser.END_TAG:
.equals(parser.getName())){
//一个城市的信息处理完毕了
weatherInfos.add(weatherInfo);
;
}
;
}
type=parser.next();
}
return weatherInfos;
}
4.主main

java.util.List;
org.xmlpull.v1.XmlPullParserException;
android.os.Bundle;
android.app.Activity;
android.widget.TextView;
MainActivity extends Activity{
TextViewtv;
@Override
protected void onCreate(BundlesavedInstanceState){
super .onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.tv);
List<WeatherInfo>infos= ;
@H_403_311@try {
infos=WeathearService
.getWeatherInfos(MainActivity. .getClassLoader()
.getResourceAsStream( "weather.xml" ));
catch (XmlPullParserExceptione){
e.printStackTrace();
(IOExceptione){
e.printStackTrace();
}
StringBuildersb= StringBuilder();
for (WeatherInfoinfo:infos){
Stringstr=info.toString();
sb.append(str);
sb.append( "\n" );
}
tv.setText(sb);
}
}

猜你在找的XML相关文章