Detailed explanation of four XML parsing methods

黄舟
Release: 2017-02-13 15:07:19
Original
1382 people have browsed it



As we all know, there are more and more ways to parse XML, but there are only four mainstream methods, namely: DOM, SAX, JDOM and DOM4J

The following will first give the jar package download addresses for these four methods

DOM: They are all included in the current Java JDK.

SAX in the xml-apis.jar package: http://www.php.cn/

JDOM: http://www.php.cn/

DOM4J :http://www.php.cn/

1. Introduction and analysis of advantages and disadvantages

1. DOM (Document Object Model)

DOM is used with platforms and The official W3C standard for representing XML documents in a language-independent way. DOM is a collection of nodes or pieces of information organized in a hierarchical structure. This hierarchy allows developers to search the tree for specific information. Analyzing this structure typically requires loading the entire document and constructing the hierarchy before any work can be done. Because it is based on information hierarchy, DOM is considered tree-based or object-based.

【Advantages】

①Allows applications to make changes to data and structures.

②Access is bidirectional. You can navigate up and down the tree at any time to obtain and operate any part of the data.

【Disadvantages】

① Usually it is necessary to load the entire XML document to construct the hierarchical structure, which consumes a lot of resources.

2. SAX (Simple API for XML)

The advantages of SAX processing are very similar to the advantages of streaming media. Analysis can begin immediately instead of waiting for all data to be processed. Also, since the application just checks the data as it is read, there is no need to store the data in memory. This is a huge advantage for large documents. In fact, the application doesn't even have to parse the entire document; it can stop parsing when a certain condition is met. In general, SAX is also much faster than its replacement, DOM.

Choose DOM or SAX? For developers who need to write their own code to process XML documents, choosing the DOM or SAX parsing model is a very important design decision. DOM uses a tree structure to access XML documents, while SAX uses an event model.

The DOM parser converts the XML document into a tree containing its content, and can traverse the tree. The advantage of using DOM to parse the model is that it is easy to program. Developers only need to call the tree-building instructions, and then use navigation APIs to access the required tree nodes to complete the task. Elements in the tree can be easily added and modified. However, since the entire XML document needs to be processed when using the DOM parser, the performance and memory requirements are relatively high, especially when encountering large XML files. Due to its traversal capabilities, DOM parsers are often used in services where XML documents need to change frequently.

The SAX parser adopts an event-based model. It can trigger a series of events when parsing XML documents. When a given tag is found, it can activate a callback method and tell the method to formulate The tag has been found. SAX usually has lower memory requirements because it allows developers to decide which tags to process. Especially when developers only need to process part of the data contained in the document, SAX's scalability is better reflect. But coding is more difficult when using a SAX parser, and it is difficult to access multiple different data in the same document at the same time.

【Advantages】

① There is no need to wait for all data to be processed, the analysis can start immediately.

②The data is only checked when reading the data and does not need to be saved in memory.

③You can stop parsing when a certain condition is met, without parsing the entire document.

④High efficiency and performance, able to parse documents larger than system memory.

[Disadvantages]

① The application needs to be responsible for the TAG processing logic (such as maintaining parent/child relationships, etc.). The more complex the document, the more complicated the program.

②One-way navigation, unable to locate the document hierarchy, difficult to access different parts of the same document at the same time, does not support XPath.

3. JDOM (Java-based Document Object Model)

The purpose of JDOM is to be a Java-specific document model that simplifies interaction with XML and is faster than using DOM. JDOM has been heavily promoted and promoted since it was the first Java-specific model. It is being considered for eventual use as a "Java Standard Extension" via "Java Specification Request JSR-102". JDOM development has been started since the early 2000s.

There are two main differences between JDOM and DOM. First, JDOM only uses concrete classes and not interfaces. This simplifies the API in some ways, but also limits flexibility. Second, the API makes extensive use of the Collections class, simplifying its use for Java developers who are already familiar with these classes.

The JDOM documentation states that its purpose is to "solve 80% (or more) Java/XML problems using 20% ​​(or less) effort" (assuming 20% ​​based on the learning curve). JDOM is certainly useful for most Java/XML applications, and most developers find the API much easier to understand than DOM. JDOM also includes fairly extensive checks on program behavior to prevent users from doing anything that doesn't make sense in XML. However, it still requires that you understand XML well enough to do more than the basics (or even understand the errors in some cases). This may be more meaningful work than learning DOM or JDOM interfaces.

JDOM itself does not contain a parser. It typically uses a SAX2 parser to parse and validate input XML documents (although it can also take previously constructed DOM representations as input). It contains converters to output JDOM representations into SAX2 event streams, DOM models, or XML text documents. JDOM is open source released under a variant of the Apache license.

【Advantages】

①Using concrete classes instead of interfaces simplifies the DOM API.

②Extensive use of Java collection classes, which is convenient for Java developers.

【Disadvantages】

①No better flexibility.

② Poor performance.

4. DOM4J (Document Object Model for Java)

Although DOM4J represents a completely independent development result, initially, it was an intelligent branch of JDOM. It incorporates many features beyond basic XML document representation, including integrated XPath support, XML Schema support, and event-based processing for large or streaming documents. It also provides options to build document representations with parallel access capabilities through the DOM4J API and standard DOM interfaces. It has been under development since the second half of 2000.

To support all these features, DOM4J uses interfaces and abstract basic class methods. DOM4J makes heavy use of the Collections class in the API, but in many cases it also provides alternatives that allow for better performance or a more direct coding approach. The direct benefit is that although DOM4J pays the price of a more complex API, it provides much greater flexibility than JDOM.

While adding flexibility, XPath integration, and the goal of processing large documents, DOM4J's goals are the same as JDOM: ease of use and intuitive operation for Java developers. It also aims to be a more complete solution than JDOM, achieving the goal of handling essentially all Java/XML problems. While accomplishing that goal, it places less emphasis than JDOM on preventing incorrect application behavior.

DOM4J is a very, very excellent Java XML API with excellent performance, powerful functions and extreme ease of use. It is also an open source software. Nowadays you can see that more and more Java software is using DOM4J to read and write XML. It is particularly worth mentioning that even Sun's JAXM is also using DOM4J.

[Advantages]

①Extensive use of Java collection classes to facilitate Java developers and provide some alternative methods to improve performance.

②Support XPath.

③Has very good performance.

【Disadvantages】

① Extensive use of interfaces, the API is relatively complex.

2. Comparison

1. DOM4J has the best performance, even Sun’s JAXM is also using DOM4J. Currently, DOM4J is widely used in many open source projects. For example, the famous Hibernate also uses DOM4J to read XML configuration files. If portability is not considered, then use DOM4J.

2. JDOM and DOM performed poorly in performance testing, with memory overflow when testing 10M documents, but they are portable. It is also worth considering using DOM and JDOM in the case of small documents. Although the developers of JDOM have stated that they expect to focus on performance issues before the official release, from a performance point of view, it really has nothing to recommend. In addition, DOM is still a very good choice. DOM implementation is widely used in many programming languages. It is also the basis for many other XML-related standards, and since it is officially recommended by the W3C (as opposed to the non-standard based Java model), it may also be required in certain types of projects (such as using the DOM in JavaScript).

3. SAX performs better, which depends on its specific parsing method - event driven. A SAX detects the incoming XML stream, but does not load it into memory (of course when the XML stream is read, some documents will be temporarily hidden in memory).

My opinion: If the XML document is large and portability is not considered, it is recommended to use DOM4J; if the XML document is small, it is recommended to use JDOM; if it needs to be processed in a timely manner without saving data, consider SAX. But in any case, the same sentence remains: the one that suits you is the best. If time permits, I suggest you try all four methods and then choose the one that suits you.

3. Example

In order to save space, we will not give the four methods and differences of creating XML documents here for the time being. We will only give the code for parsing XML documents. If you need a complete project (create XML document + Parse XML + test comparison).

Here is the following XML content as an example for analysis:

<?xml version="1.0" encoding="UTF-8"?>
<users>
    <user id="0">
        <name>Alexia</name>
        <age>23</age>
        <sex>Female</sex>
    </user>
    <user id="1">
        <name>Edward</name>
        <age>24</age>
        <sex>Male</sex>
    </user>
    <user id="2">
        <name>wjm</name>
        <age>23</age>
        <sex>Female</sex>
    </user>
    <user id="3">
        <name>wh</name>
        <age>24</age>
        <sex>Male</sex>
    </user>
</users>
Copy after login

First define the interface for XML document parsing:

/**
 * @author Alexia
 *
 * 定义XML文档解析的接口
 */
public interface XmlDocument {
     
	/**
	* 解析XML文档
	* 
	* @param fileName
	*            文件全路径名称
	*/
	public void parserXml(String fileName);
}
Copy after login

1. DOM example

package com.xml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * 
 * DOM 解析XML文档
 */
public class DomDemo implements XmlDocument {
    private Document document;

    public void parserXml(String fileName) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(fileName);
            NodeList users = document.getChildNodes();
            
            for (int i = 0; i < users.getLength(); i++) {
                Node user = users.item(i);
                NodeList userInfo = user.getChildNodes();
                
                for (int j = 0; j < userInfo.getLength(); j++) {
                    Node node = userInfo.item(j);
                    NodeList userMeta = node.getChildNodes();
                    
                    for (int k = 0; k < userMeta.getLength(); k++) {
                        if(userMeta.item(k).getNodeName() != "#text")
                            System.out.println(userMeta.item(k).getNodeName()
                                    + ":" + userMeta.item(k).getTextContent());
                    }
                    
                    System.out.println();
                }
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Copy after login

2. SAX example

package com.xml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.DefaultHandler;

/**
 * 
 * SAX 解析XML文档
 */
public class SaxDemo implements XmlDocument {

    public void parserXml(String fileName) {
        SAXParserFactory saxfac = SAXParserFactory.newInstance();

        try {
            SAXParser saxparser = saxfac.newSAXParser();
            InputStream is = new FileInputStream(fileName);
            saxparser.parse(is, new MySAXHandler());
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class MySAXHandler extends DefaultHandler {
    boolean hasAttribute = false;
    Attributes attributes = null;

    public void startDocument() throws SAXException {
        // System.out.println("文档开始打印了");
    }

    public void endDocument() throws SAXException {
        // System.out.println("文档打印结束了");
    }

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        if (qName.equals("users")) {
            return;
        }
        if (qName.equals("user")) {
            return;
        }
        if (attributes.getLength() > 0) {
            this.attributes = attributes;
            this.hasAttribute = true;
        }
    }

    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (hasAttribute && (attributes != null)) {
            for (int i = 0; i < attributes.getLength(); i++) {
                System.out.print(attributes.getQName(0) + ":"
                        + attributes.getValue(0));
            }
        }
    }

    public void characters(char[] ch, int start, int length)
            throws SAXException {
        System.out.print(new String(ch, start, length));
    }
}
Copy after login

3. JDOM example

package com.xml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.XMLOutputter;

/**
 * 
 * JDOM 解析XML文档
 * 
 */
public class JDomDemo implements XmlDocument {

    public void parserXml(String fileName) {
        SAXBuilder builder = new SAXBuilder();

        try {
            Document document = builder.build(fileName);
            Element users = document.getRootElement();
            List userList = users.getChildren("user");

            for (int i = 0; i < userList.size(); i++) {
                Element user = (Element) userList.get(i);
                List userInfo = user.getChildren();

                for (int j = 0; j < userInfo.size(); j++) {
                    System.out.println(((Element) userInfo.get(j)).getName()
                            + ":" + ((Element) userInfo.get(j)).getValue());

                }
                System.out.println();
            }
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
Copy after login

4. DOM4J example

package com.xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 
 * Dom4j 解析XML文档
 */
public class Dom4jDemo implements XmlDocument {

    public void parserXml(String fileName) {
        File inputXml = new File(fileName);
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(inputXml);
            Element users = document.getRootElement();
            for (Iterator i = users.elementIterator(); i.hasNext();) {
                Element user = (Element) i.next();
                for (Iterator j = user.elementIterator(); j.hasNext();) {
                    Element node = (Element) j.next();
                    System.out.println(node.getName() + ":" + node.getText());
                }
                System.out.println();
            }
        } catch (DocumentException e) {
            System.out.println(e.getMessage());
        }
    }

}
Copy after login

The above is the detailed explanation of the four XML parsing methods. Please pay attention to more related content. PHP Chinese website (www.php.cn)!

Related labels:
xml
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template