使用pull方式和sax方式对xml文件进行解析
这是我自己设置的xml文件
用一下方式获取它的内容
try{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
//对于虚拟机而言的本地地址
.url("http://10.0.2.2/get_data.xml")
.build();
Response response =client.newCall(request).execute();
String responseData = response.body().string();
}catch (Exception e){
e.printStackTrace();
}
首先是pull方式
xmlData是获取到的xml文件内容
private void parseXMLWithPull(String xmlData){
try{
Log.i(TAG, "parseXMLWithPull: ");
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:{
switch (nodeName){
case "id":
id = xmlPullParser.nextText();
break;
case "name":
name = xmlPullParser.nextText();
break;
case "version":
version = xmlPullParser.nextText();
break;
default:
break;
}
break;
}
//结束解析某个节点
case XmlPullParser.END_TAG:{
if("app".equals(nodeName)){
Log.i(TAG, "id: "+id);
Log.i(TAG, "name: "+name);
Log.i(TAG, "version: "+version);
}
break;
}
default:
break;
}
eventType = xmlPullParser.next();
}
}catch (Exception e){
e.printStackTrace();
}
}
然后是Sax方式,这种方式需要新建一个类并使它继承defaultHandler类
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 {
switch (nodeName){
case "id": {
id.append(ch, start, length);
break;
}
case "name":{
name.append(ch,start,length);
break;
}
case "version":{
version.append(ch,start,length);
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if("app".equals(nodeName)){
Log.i("ContentHandler", "id: "+id.toString().trim());
Log.i("ContentHandler", "name: "+name.toString().trim());
Log.i("ContentHandler", "version: "+version.toString().trim());
//清空StringBuilder
id.setLength(0);
name.setLength(0);
version.setLength(0);
}
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
}