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();
//得到事件类型
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"
@H_656_404@Stringname=parser.nextText();
.equals(parser.getName())){