首页 > 代码库 > DOM/SAX/PULL解析XML

DOM/SAX/PULL解析XML

1. 代码结构

  

  InterfaceXMLParseService 解析接口, DOM/SAX/PULL分别实现这个接口

  

  XML来源是assets目录下的persons.xml文件

 

2. 代码

//persons.xml<?xml version="1.0" encoding="utf-8"?><persons>    <person>        <id>1</id>        <name>Tom</name>        <age>12</age>    </person>    <person>        <id>2</id>        <name>May</name>        <age>14</age>    </person>    <person>        <id>3</id>        <name>Joe</name>        <age>13</age>    </person></persons>

 

//XMLParserServicepackage mirror.android.XMLParseActivity;import java.io.IOException;import java.io.InputStream;import mirror.android.Services.DOMParseService;import mirror.android.Services.PULLParseService;import mirror.android.Services.SAXParseService;import mirror.android.resolvexml.R;import android.app.Activity;import android.os.Bundle;public class XMLParseActivity extends Activity{    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_xmlparse);                try {                        InputStream in1 = getAssets().open("persons.xml");            InputStream in2 = getAssets().open("persons.xml");            InputStream in3 = getAssets().open("persons.xml");                        DOMParseService domParseService = new DOMParseService();            domParseService.getPersonsByParseXML(in1);                        SAXParseService saxParseService = new SAXParseService();            saxParseService.getPersonsByParseXML(in2);                        PULLParseService pullParseService = new PULLParseService();            pullParseService.getPersonsByParseXML(in3);                    } catch (IOException e) {            e.printStackTrace();        }    }}
//InterfaceXMLParserService.javapackage mirror.android.Services;import java.io.InputStream;public interface InterfaceXMLParseService {    public void getPersonsByParseXML(InputStream is);}
//DOMParserService.javapackage mirror.android.Services;import java.io.InputStream;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import android.util.Log;/* DOM解析器在解析XML文档时,会把文档中的所有元素,       按照其出现的层次关系,解析成一个个Node对象(节点)。Node对象提供了一系列常量来代表结点的类型       当开发人员获得某个Node类型后,就可以把Node节点转换成相应节点对象(Node的子类对象),以便于调用其特有的方法。   Node对象提供了相应的方法去获得它的父结点或子结点。编程人员通过这些方法就可以读取整个XML文档的内容、或添加、修改、删除XML文档的内容.       缺点:             一次性的完全加载整个xml文件,需要消耗大量的内存。*/public class DOMParseService implements InterfaceXMLParseService{    @Override    public void getPersonsByParseXML(InputStream is){                try {            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();            DocumentBuilder db = dbf.newDocumentBuilder();            Document doc = db.parse(is);            doc.getDocumentElement().normalize();                        //得到根元素,这里是persons            NodeList personNodes = doc.getElementsByTagName("person");                        //Log.d("Mirror", personNodes.toString() + " its length is " + personNodes.getLength());                        for (int i = 0; i < personNodes.getLength(); i++) {                Element element_person = (Element)personNodes.item(i);                                Node node_id = element_person.getElementsByTagName("id").item(0);                Node node_name = element_person.getElementsByTagName("name").item(0);                Node node_age = element_person.getElementsByTagName("age").item(0);                                Log.d("DOMParse--->","Name: " + node_name.getFirstChild().getNodeValue()                                      + ", Id: " + node_id.getFirstChild().getNodeValue()                                      + ", age: "+ node_age.getFirstChild().getNodeValue());            }        }         catch (Exception e) {            e.printStackTrace();        }    }}
//SAXParserService.javapackage mirror.android.Services;import java.io.InputStream;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import android.util.Log;//优点:SAX解析允许在读取文档的时候,即对文档进行处理,而不必等到整个文档装载完才会文档进行操作。public class SAXParseService implements InterfaceXMLParseService {    @Override    public void getPersonsByParseXML(InputStream is) {                try {            SAXParserFactory factory = SAXParserFactory.newInstance();            SAXParser parser = factory.newSAXParser();            parser.parse(is, new saxHandler());        } catch (Exception e) {            e.printStackTrace();        }    }        // 自定义一个handler实现DefaultHandler并 重写它的相关方法    private class saxHandler extends DefaultHandler{                private String currentTag = null;                String str = "";        @Override        public void startDocument() throws SAXException {            //读到 <?xml version="1.0" encoding="utf-8"?> 时调用        }        @Override        public void endDocument() throws SAXException {        }        @Override        public void startElement(String uri, String localName, String qName,                Attributes attributes) throws SAXException {            //if("person".equals(localName));            currentTag = localName;            //Log.d("Mirror_startElement",localName);        }        @Override        public void endElement(String uri, String localName, String qName)                throws SAXException {            //Log.d("Mirror_endElement",localName);            if(localName.equals(currentTag))                currentTag = null;        }        @Override        public void characters(char[] ch, int start, int length)                throws SAXException {            if("id".equals(currentTag))                str += "Id: " + new String(ch,start,length);            if("name".equals(currentTag))                str += ",Name: " + new String(ch,start,length);            if("age".equals(currentTag)){                str += ",Age: " + new String(ch,start,length);                Log.d("SAXParse--->", str);                str = "";            }        }    }}
//PULLParserService.javapackage mirror.android.Services;import java.io.InputStream;import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserFactory;import android.util.Log;//优点:不是一次加载,中途可以停止。public class PULLParseService implements InterfaceXMLParseService {    @Override    public void getPersonsByParseXML(InputStream is) {                String str = "";                try {            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();            XmlPullParser parser = factory.newPullParser();            parser.setInput(is,"utf-8");                        //parser的几种事件类型            int type = parser.getEventType();            while(type != XmlPullParser.END_DOCUMENT){                String typeName = parser.getName();                switch (type) {                    case XmlPullParser.START_DOCUMENT:                        break;                    case XmlPullParser.START_TAG:                        if("person".equals(typeName));                        else if("id".equals(typeName))                            str += "Id: " + parser.nextText();                        else if("name".equals(typeName))                            str += ", name " + parser.nextText();                        else if("age".equals(typeName)){                            str += ", age " + parser.nextText();                            Log.d("PULLParse--->", str);                            str = "";                        }                        break;                    case XmlPullParser.END_TAG:                        break;                    default:                        break;                }                //Get next parsing event.最最重要的一步,pull解析中的特有的方法,解析下一个标签                type = parser.next();            }                    } catch (Exception e) {            e.printStackTrace();        }    }}

 

3. 打印结果

  

 

4. 项目地址

  https://github.com/Mirrorhanyu/XMLParser

 

DOM/SAX/PULL解析XML