Pull解析
首先获取到一个XmlPullParserFactory的实例,再调用setInput()方法将xml数据返回到当前的事件。通过getEventtype()方法可以得到当前的解析事件
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(new StringReader(xmlData));
int eventType = xmlPullParser.getEventType();
再在while循环中不断解析,如果当前事件不等于XmlPullParser.END_DOCUMENT,说明解析没有完成,调用next()方法后可以获取下一个解析事件,在循环中,用getName来获取当前节点的名字,然后调用nextText()方法获得节点内容。
这里有一份准备好的数据文件。
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("id",id);
Log.d("name",name);
Log.d("version",version);
}
break;
}
}
eventType = xmlPullParser.next();
}
SAX解析
SAX用法比Pull要复杂一些,但是语义方面会更加清楚。通常情况下新建一个类并且继承DefaultHandler,并重写父类的5个方法
public class MyHandler extends DefaultHandler {
private String nodeName;
private StringBuilder id;
private StringBuilder name;
private StringBuilder version;
//开始XML解析时调用
@Override
public void startDocument() throws SAXException {
id = new StringBuilder();
name = new StringBuilder();
version = new StringBuilder();
}
//开始解析某个节点时调用
@Override
public void startElement(String uri,String localName,String qName,Attributes
attributes) throws SAXException {
nodeName = localName;
}
//获取节点内容时调用
@Override
public void characters(char[] ch,int start,int length) throws SAXException {
if("id".equals(nodeName)){
id.append(ch,start,length);
}else if("name".equals(nodeName)){
name.append(ch,length);
}else if("version".equals(nodeName)){
version.append(ch,length);
}
}
//完成解析某个节点时调用
@Override
public void endElement(String uri,String qName) throws
SAXException {
if("app".equals(nodeName)){
Log.d("id",id.toString().trim());
Log.d("name",name.toString().trim());
Log.d("version",version.toString().trim());
//清空StringBuilder
id.setLength(0);
name.setLength(0);
version.setLength(0);
}
}
//完成解析XML时调用
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
}
接下来的工作和Pull差不多
SAXParserFactory factory = SAXParserFactory.newInstance();
XMLReader xmlReader = factory.newSAXParser().getXMLReader();
MyHandler handler = new MyHandler();
xmlReader.setContentHandler(handler);
//开始执行解析
xmlReader.parse(new InputSource(new StringReader(xmlData)));