xml解析案例
步驟: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;
}
xml解析案例