private void parseXMLWithPull(String xmlData){
try{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(new StringReader(xmlData));
int eventType = xmlPullParser.getEventType();
String id = "";
String name = "";
String version = "";
while (eventType != XmlPullParser.END_DOCUMENT){
String nodeName = xmlPullParser.getName();
switch (eventType){
//开始解析某个节点
case XmlPullParser.START_TAG:
if("id".equals(nodeName)){
id = xmlPullParser.nextText();
}else if("name".equals(nodeName)) {
name = xmlPullParser.nextText();
}else if("version".equals(nodeName)){
version = xmlPullParser.nextText();
}
break;
//完成解析某个节点
case XmlPullParser.END_TAG:
if("app".equals(nodeName)){
Log.d(TAG, "id is " +id);
Log.d(TAG, "name is " +name);
Log.d(TAG, "version is " +version);
}
break;
default:
break;
}
eventType = xmlPullParser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
}
测试结果
,用getEventType()得到当前的解析事件。用getName()得到节点的名字。