Android-XML parsing (DOM, SAX, PULL)

I would like to record the learning process with articles, and please indicate if there are any mistakes.

Introduction to XML

XML stands for Extensible Markup Language, and we understand it from two perspectives:

  1. Extensible: use it for any purpose: configuration file, UI description file, etc.
  2. Markup Language: HTML (Hypertext Markup Language) is also a markup language, and HTML can be seen as a sublanguage of XML.

From the above two points, XML is a specification of document structure. The content of the document can be anything according to your needs. Description configuration files, such as Spring's many configuration files; UI descriptions, such as HTML and Android layout files.

XML he only defines the structure of the document: pairs of tags, the location of attributes and so on. It's up to you to decide what you parse into these tags and attributes.


XML parsing

  • Purpose: Extract the data we need from XML
  • Classification:
Analysis method Implementation principle specific type
Document driven Read the entire contents of the XML file into memory before parsing DOM method
event driven Perform different parsing operations according to different demand events SAX method
Pull method

Demo site

DemoXML-Json

Sample xml file (located under the project assets path)

<apps>
    <app>
        <id>1</id>
        <name>Google Maps</name>
        <version>1.0</version>
    </app>
    <app>
        <id>2</id>
        <name>Chrome</name>
        <version>2.1</version>
    </app>
    <app>
        <id>3</id>
        <name>Google Play</name>
        <version>2.3</version>
    </app>
</apps>

DOM parsing

  • Introduction

    • DOM stands for Document Object ModelDocument Object Model
    • A DOM-based XML parser converts an XML document into a collection of object models (often called a DOM tree)
    • Through the DOM interface, the application can access any part of the data in the XML document at any time. Therefore, this mechanism using the DOM interface is also called the random access mechanism.
    • Use the DOM API to traverse the DOM tree and retrieve the required data;
  • Features:
    Advantages:

    1. A tree structure is formed, which is helpful for better understanding and mastery, and the code is easy to write.
    2. During the parsing process, the tree structure is stored in memory for easy modification.

    shortcoming:

    1. Since the file is read at one time, the memory consumption is relatively large.
    2. If the XML file is relatively large, it is easy to affect the parsing performance and may cause memory overflow
  • Parse instance
private void xml_dom(){
        StringBuilder data = new StringBuilder();
        try {
            //打开assets文件夹下的xml示例文件到输入流
            InputStream in = getAssets().open("example.xml");
            //得到Document Builder Factory对象
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            //得到Document Builder对象
            DocumentBuilder builder = builderFactory.newDocumentBuilder();
            //得到Document存放整个xml的Document对象数据
            Document document = builder.parse(in);
            //得到xml数据的根节点
            Element rootElement = document.getDocumentElement();
            //得到根节点下所有app节点
            NodeList list = rootElement.getElementsByTagName("app");
            //遍历所有节点
            for (int i = 0;i < list.getLength(); i++){
                //获取app节点的所有子元素
                Element app = (Element) list.item(i);
                //获取app节点的子元素id,name,version,并添加到StringBuilder中
                data.append("id is " + app.getElementsByTagName("id").item(0).getTextContent() + "\n");
                data.append("name is " + app.getElementsByTagName("name").item(0).getTextContent() + "\n");
                data.append("version is " + app.getElementsByTagName("version").item(0).getTextContent() + "\n");
            }
            //更新UI
            dataText.setText(data);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

SAX parsing

  • Introduction
    • The full name of SAX is Simple APIs for XML, which is the XML Simple Application Programming Interface
    • The access mode provided by SAX is a sequential mode, which is a fast way to read and write XML data
    • When using the SAX analyzer to analyze the XML document, a series of events will be triggered, and the corresponding event handling functions will be activated, and the application program will access the XML document through these event handling functions.
  • Features
    Benefits

    1. Using event-driven mode, the parsing speed is fast, and it takes up less memory
    2. Great for use in Android mobile devices

    shortcoming

    1. Coding is cumbersome.
    2. It is difficult to access multiple different data in XML files at the same time.
  • Parse instance

/**
     * SAX方式解析:需要新建类继承自DefaultHandler类,并重写弗雷德5个方法,如下所示
     */
    class ContentHandler extends DefaultHandler{

        private String nodeName;

        private StringBuilder id;

        private StringBuilder name;

        private StringBuilder version;

        private StringBuilder text;

        //在开始XML解析的时候调用
        @Override
        public void startDocument() throws SAXException {
            id = new StringBuilder();
            name = new StringBuilder();
            version = new StringBuilder();
            text = 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, start, length);
            }else if ("version".equals(nodeName)){
                version.append(ch, start, length);
            }
        }

        //在对某个节点的解析完成时调用
        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            if ("app".equals(localName)){
                text.append("id is " + id.toString() + "\n");
                text.append("name" + name.toString() + "\n");
                text.append("version is " + version.toString() + "\n");
                id.setLength(0);
                name.setLength(0);
                version.setLength(0);
            }
        }

        //整个XML解析完成的时候调用
        @Override
        public void endDocument() throws SAXException {
            dataText.setText(text);
            super.endDocument();

        }
    }

    private void xml_sax(){
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            ContentHandler mHandler = new ContentHandler();
            //打开assets文件夹下的xml示例文件到输入流
            InputStream in = getAssets().open("example.xml");
            parser.parse(in,mHandler);

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

Pull analysis

  • Introduction
    • The PULL parser operates in a similar way to SAX, both in an event-based mode.
    • The difference is that in the PULL parsing process, we need to get the generated events and do the corresponding operations ourselves, instead of the processor triggering an event method like SAX to execute our code.
  • Features
    Benefits

    1. PULL parser is small and lightweight, fast parsing, easy to use
    2. High flexibility, free control of access timing
    3. It is very suitable for use in Android mobile devices. The Android system also uses PULL parser when parsing various XML.

    shortcoming

    1. Poor scalability, unable to modify the XML tree content structure
  • Parse instance
private void xml_pull(){
        /*
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(new StringReader(xmlData));
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        }*/


        StringBuilder builder = new StringBuilder("");
        XmlPullParser parser = Xml.newPullParser();

        try {
            //打开assets文件夹下的xml示例文件到输入流
            InputStream in = getAssets().open("example.xml");
            parser.setInput(in,"UTF-8");
            while (parser.getEventType() != XmlPullParser.END_DOCUMENT){

                String nodeName = parser.getName();
                int eventType = parser.getEventType();
                switch (eventType){
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        if ("id".equals(nodeName)){
                            builder.append("id is : " + parser.nextText() + "\n");
                        }else if ("name".equals(nodeName)){
                            builder.append("name is : "+ parser.nextText() + "\n");
                        }else if ("version".equals(nodeName)){
                            builder.append("version is : "+ parser.nextText() + "\n");
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                parser.next();
            }
            dataText.setText(builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Summarize

  • This article summarizes three ways of parsing XML in Android
  • Later, I will introduce another mainstream data transmission format JSON. For details, please go to Android-JSON parsing (Gson, org.json, Jackson, FastJson)
  • The author's level is limited, if there are any mistakes or omissions, please correct me.
  • Next, I will also share the knowledge I have learned. If you are interested, you can continue to pay attention to the Android development notes of whd_Alive.
  • I will share technical dry goods related to Android development from time to time, and look forward to communicating and encouraging with you.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326072907&siteId=291194637