读取数据
String xmlString = "";XmlPullParserFactory factory = XmlPullParserFactory.newInstance();//创建工厂用于创建XmlPullParser解析器 XmlPullParser xmlPullParser = factory.newPullParser(); //创建解析器 xmlPullParser.setInput(new StringReader(xmlString));
解析数据
XmlPullParser response= xmlPullParser;int eventType = response.getEventType();while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: String nodeName = response.getName(); if ("city".equals(nodeName)) { String pName = response.getAttributeValue(0); Log.d("Bob", "pName is " + pName); } break; } eventType = response.next();}官方代码
public class SimpleXmlPullApp { public static void main (String args[]) throws XmlPullParserException, IOException { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput( new StringReader ( "Hello World! " ) ); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if(eventType == XmlPullParser.START_DOCUMENT) { System.out.println("Start document"); } else if(eventType == XmlPullParser.START_TAG) { System.out.println("Start tag "+xpp.getName()); } else if(eventType == XmlPullParser.END_TAG) { System.out.println("End tag "+xpp.getName()); } else if(eventType == XmlPullParser.TEXT) { System.out.println("Text "+xpp.getText()); } eventType = xpp.next(); } System.out.println("End document"); } }