步骤:Channel是java bean类
public static List<Channel> parsexml(InputStream inputStream) {
//0声明集合对象和java bean对象
List<Channel>weatherList = null;
Channel channel = null;
//1获取XmlPullParser 解析的实例
XmlPullParser parser = Xml.newPullParser();
try {
//2设置XmlPullParser 的参数
parser.setInput(inputStream,"utf-8");
//3获取事件类型
int eventType = parser.getEventType();
//4循环解析并存储
while(eventType!=XmlPullParser.END_DOCUMENT){
switch (eventType) {
case XmlPullParser.START_TAG://解析开始的标签
//5具体判断解析到哪一个标签
if ("weather".equals(parser.getName())) {
//6实例化一个集合对象
weatherList = new ArrayList<>();
} else if ("channel".equals(parser.getName())) {
//7實例化一个java bean对象
channel = new Channel();
//8获取id值并且保存
String id = parser.getAttributeValue(0);
channel.setId(id);
} else if ("city".equals(parser.getName())) {
//9获取city值并且保存
try {
String city = parser.nextText();
channel.setCity(city);
} catch (IOException e) {
e.printStackTrace();
}
}else if ("temp".equals(parser.getName())) {
//10获取city值并且保存
try {
String temp = parser.nextText();
channel.setTemp(temp);
} catch (IOException e) {
e.printStackTrace();
}
}else if ("wind".equals(parser.getName())) {
//11获取city值并且保存
try {
String wind = parser.nextText();
channel.setWind(wind);
} catch (IOException e) {
e.printStackTrace();
}
}else if ("pm250".equals(parser.getName())) {
//12获取city值并且保存
try {
String pm250 = parser.nextText();
channel.setPm250(pm250);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case XmlPullParser.END_TAG://结束标签
if ("channel".equals(parser.getName())) {
//把javabean对象存到集合中
weatherList.add(channel);
}
break;
}
//不停的向下解析
try {
eventType = parser.next();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return weatherList;
}