XmlPullParser对象android专用的XML解析方式- public class WeatherService {
- /**
- *
- *
- * @param in
- * @return
- */
- public static List<Channel> getWeather(InputStream in) {
- // 1
- XmlPullParser parser = Xml.newPullParser();
- // 2
- try {
- parser.setInput(in, "utf-8");
- List<Channel> smsLists = null;
- Channel channel = null;
- // 3
- int type = parser.getEventType(); //
- while (type != XmlPullParser.END_DOCUMENT) { //
- switch (type) {
- case XmlPullParser.START_TAG:
- if ("weather".equals(parser.getName())) {
- smsLists = new ArrayList<Channel>();
- } else if ("channel".equals(parser.getName())) {
- channel = new Channel();
- String id = parser.getAttributeValue(0);
- channel.setId(id);
- } else if ("city".equals(parser.getName())) {
- String city = parser.nextText();
- channel.setCity(city);
- } else if ("temp".equals(parser.getName())) {
- String temp = parser.nextText();
- channel.setTemp(temp);
- } else if ("wind".equals(parser.getName())) {
- String wind = parser.nextText();
- channel.setWind(wind);
- } else if ("pm2.5".equals(parser.getName())) {
- String pm250 = parser.nextText();
- channel.setPm250(pm250);
- }
- break;
- case XmlPullParser.END_TAG:
- if ("channel".equals(parser.getName())) {
- smsLists.add(channel);
- }
- break;
- default:
- break;
- }
- type = parser.next();
- }
- return smsLists;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- }
复制代码 |