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> <name>Alexia</name> <age>23</age> <sex>Female</sex> </user> <user> <name>Edward</name> <age>24</age> <sex>Male</sex> </user> <user> <name>wjm</name> <age>23</age> <sex>Female</sex> </user> <user> <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 <h2 id="SAX-example"> 2. SAX example </h2><pre class="brush:php;toolbar:false">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 <h2 id="JDOM-example">3. JDOM example </h2><pre class="brush:php;toolbar:false">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 <h2 id="DOM-J-example">4. DOM4J example </h2><pre class='brush:php;toolbar:false;'>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 (www.php.cn)!

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.

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.

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.

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.

RSS is an XML-based format used to subscribe and read frequently updated content. Its working principle includes two parts: generation and consumption, and using an RSS reader can efficiently obtain information.

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.

The main differences between JSON, XML and RSS are structure and uses: 1. JSON is suitable for simple data exchange, with a simple structure and easy to parse; 2. XML is suitable for complex data structures, with a rigorous structure but complex parsing; 3. RSS is based on XML and is used for content release, standardized but limited use.

The processing of XML/RSS feeds involves parsing and optimization, and common problems include format errors, encoding issues, and missing elements. Solutions include: 1. Use XML verification tools to check for format errors; 2. Ensure encoding consistency and use the chardet library to detect encoding; 3. Use default values or skip the element when missing elements; 4. Use efficient parsers such as lxml and cache parsing results to optimize performance; 5. Pay attention to data consistency and security to prevent XML injection attacks.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor
