search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
1. Introduction and analysis of advantages and disadvantages
1. DOM (Document Object Model)
2. SAX (Simple API for XML)
3. JDOM (Java-based Document Object Model)
4. DOM4J (Document Object Model for Java)
2. Comparison
3. Example
1. DOM example
2. SAX example
3. JDOM example
4. DOM4J example
Home Backend Development XML/RSS Tutorial Detailed explanation of four XML parsing methods

Detailed explanation of four XML parsing methods

Feb 13, 2017 pm 03:07 PM
xml 解析方式



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: //m.sbmmt.com/

JDOM: //m.sbmmt.com/

DOM4J ://m.sbmmt.com/

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>

First define the interface for XML document parsing:

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

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();
        }
    }
}

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));
    }
}

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();
        }

    }
}

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());
        }
    }

}

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

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

JSON vs. XML: Why RSS Chose XML JSON vs. XML: Why RSS Chose XML May 05, 2025 am 12:01 AM

RSS chose XML instead of JSON because: 1) XML's structure and verification capabilities are better than JSON, which is suitable for the needs of RSS complex data structures; 2) XML was supported extensively at that time; 3) Early versions of RSS were based on XML and have become a standard.

Understanding RSS Documents: A Comprehensive Guide Understanding RSS Documents: A Comprehensive Guide May 09, 2025 am 12:15 AM

RSS documents are a simple subscription mechanism to publish content updates through XML files. 1. The RSS document structure consists of and elements and contains multiple elements. 2. Use RSS readers to subscribe to the channel and extract information by parsing XML. 3. Advanced usage includes filtering and sorting using the feedparser library. 4. Common errors include XML parsing and encoding issues. XML format and encoding need to be verified during debugging. 5. Performance optimization suggestions include cache RSS documents and asynchronous parsing.

Building XML Applications with C  : Practical Examples Building XML Applications with C : Practical Examples May 03, 2025 am 12:16 AM

You can use the TinyXML, Pugixml, or libxml2 libraries to process XML data in C. 1) Parse XML files: Use DOM or SAX methods, DOM is suitable for small files, and SAX is suitable for large files. 2) Generate XML file: convert the data structure into XML format and write to the file. Through these steps, XML data can be effectively managed and manipulated.

RSS, XML and the Modern Web: A Content Syndication Deep Dive RSS, XML and the Modern Web: A Content Syndication Deep Dive May 08, 2025 am 12:14 AM

RSS and XML are still important in the modern web. 1.RSS is used to publish and distribute content, and users can subscribe and get updates through the RSS reader. 2. XML is a markup language and supports data storage and exchange, and RSS files are based on XML.

XML in C  : Handling Complex Data Structures XML in C : Handling Complex Data Structures May 02, 2025 am 12:04 AM

Working with XML data structures in C can use the TinyXML or pugixml library. 1) Use the pugixml library to parse and generate XML files. 2) Handle complex nested XML elements, such as book information. 3) Optimize XML processing code, and it is recommended to use efficient libraries and streaming parsing. Through these steps, XML data can be processed efficiently.

Beyond Basics: Advanced RSS Features Enabled by XML Beyond Basics: Advanced RSS Features Enabled by XML May 07, 2025 am 12:12 AM

RSS enables multimedia content embedding, conditional subscription, and performance and security optimization. 1) Embed multimedia content such as audio and video through tags. 2) Use XML namespace to implement conditional subscriptions, allowing subscribers to filter content based on specific conditions. 3) Optimize the performance and security of RSSFeed through CDATA section and XMLSchema to ensure stability and compliance with standards.

Inside the RSS Document: Essential XML Tags and Attributes Inside the RSS Document: Essential XML Tags and Attributes May 03, 2025 am 12:12 AM

The core structure of RSS documents includes XML tags and attributes. The specific parsing and generation steps are as follows: 1. Read XML files, process and tags. 2. Extract,,, etc. tag information. 3. Handle custom tags and attributes to ensure version compatibility. 4. Use cache and asynchronous processing to optimize performance to ensure code readability.

Decoding RSS: An XML Primer for Web Developers Decoding RSS: An XML Primer for Web Developers May 06, 2025 am 12:05 AM

RSS is an XML-based format used to publish frequently updated data. As a web developer, understanding RSS can improve content aggregation and automation update capabilities. By learning RSS structure, parsing and generation methods, you will be able to handle RSSfeeds confidently and optimize your web development skills.

Related articles