XmlPullParser的使用

XmlPullParser---基于事件解析xml

//调用xml解析函数(xml文件快速转为InputStream)
pullParserXml(getClassLoader().getResourceAsStream("weather.xml"));
//xml解析函数的实现
public static List<Channel> pullParserXml(InputStream in){
		Channel channel = null;
		List<Channel> weathers = null;
		//得到xml解析器(以事件为基础解析)
		XmlPullParser xpp = Xml.newPullParser();
		try {
			//初始化解析器,需要一个InputStream作为参数
			xpp.setInput(in, "utf-8");
			//获取事件类型
			int nEventType = xpp.getEventType();
			//循环解析
			while(nEventType != XmlPullParser.END_DOCUMENT){
				switch (nEventType) {
				case XmlPullParser.START_TAG:
					//比较标签名称
					if("weather".equals(xpp.getName())){
						weathers = new ArrayList<Channel>();
					}else if("channel".equals(xpp.getName())){
						channel = new Channel();
					}else if("city".equals(xpp.getName())){
						channel.setStrCity(xpp.nextText());
					}else if("temp".equals(xpp.getName())){
						channel.setStrTemp(xpp.nextText());
					}else if("wind".equals(xpp.getName())){
						channel.setStrWind(xpp.nextText());
					}		
					break;
				case XmlPullParser.END_TAG:
					if("channel".equals(xpp.getName())){
						weathers.add(channel);
						channel = null;
					}

				default:
					break;
				}
				
				nEventType = xpp.next();
				
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return weathers;
		
	}





你可能感兴趣的:(xmlpullparser)