Four operations in Java (DOM, sax, Jdom, dom4j) XML in a detailed and comparative way

Source: Internet
Author: User
Tags gettext xpath

1) DOM (JAXP Crimson Parser)
DOM is the official standard for representing XML documents in a platform-and language-neutral way. The DOM is a collection of nodes or pieces of information that are organized in a hierarchical structure. This hierarchy allows developers to look for specific information in the tree. Analyzing the structure usually requires loading the entire document and constructing the hierarchy before any work can be done. Because it is based on the information hierarchy, the DOM is considered to be tree-based or object-based. Dom and the generalized tree-based processing have several advantages. First, because the tree is persistent in memory, you can modify it so that the application can make changes to the data and structure. It can also navigate up and down the tree at any time, rather than a one-off process like sax. Dom is much simpler to use.

2) SAX

The advantages of Sax processing are very similar to the advantages of streaming media. The analysis can begin immediately, rather than waiting for all data to be processed. Also, because the application examines data only when it is being read, it does not 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 condition is met. In general, Sax is much faster than its surrogate dom.

Select Dom or choose Sax? Choosing the DOM or Sax parsing model is a very important design decision for developers who need to write their own code to handle XML documents. Dom uses a tree-structured approach to accessing XML documents, and the event model that Sax uses.

The DOM parser transforms an XML document into a tree containing its contents and can traverse the tree. The advantage of parsing a model with DOM is that programming is easy, and developers simply need to invoke the build instructions and then use the navigation APIs to access the desired tree nodes to complete the task. It is easy to add and modify elements in the tree. However, because of the need to process the entire XML document when using the DOM parser, the performance and memory requirements are high, especially when encountering large XML files. Because of its traversal capabilities, DOM parsers are often used in services where XML documents require frequent changes.

The SAX parser uses an event-based model that can trigger a sequence of events when parsing an XML document, and when a given tag is found, it can activate a callback method that tells the method that the label has been found. Sax's requirements for memory are usually low because it lets the developer decide which tag to process. Especially if the developer only needs to work with some of the data contained in the document, Sax has a better ability to scale. But it is difficult to code with a SAX parser, and it is difficult to access multiple different data in the same document at the same time.

3) JDOM http://www.jdom.org

The purpose of Jdom is to become a Java-specific document model that simplifies interacting with XML and is faster than using DOM implementations. Because it is the first Java-specific model, JDOM has been vigorously promoted and promoted. is considering using Java Spec request JSR-102 to end it as a Java standard extension. Since the beginning of 2000, Jdom has been developed.

There are two main differences between Jdom and Dom. First, Jdom uses only specific classes rather than interfaces. This simplifies the API in some ways, but it also limits flexibility. Second, the API uses the collections class extensively, simplifying the use of Java developers who are already familiar with these classes.

The purpose of the Jdom document declaration is to "use 20% (or less) effort to resolve 80% (or more) java/xml problems" (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 the DOM. Jdom also includes fairly extensive checks of program behavior to prevent users from doing anything meaningless in XML. However, it still requires you to fully understand the XML to do something that goes beyond basic work (or even understand some of the errors in some cases). This may be more meaningful than learning the DOM or Jdom interface.

The jdom itself does not contain parsers. It usually uses the SAX2 parser to parse and validate the input XML document (although it can also use the previously constructed DOM representation as input). It contains converters to output jdom representations to SAX2 event streams, DOM models, or XML text documents. Jdom is an open source published under the Apache license variant.

4) dom4j Http://dom4j.sourceforge.net

Although DOM4J represents a completely independent development result, initially it is an intelligent branch of Jdom. It incorporates a number of features beyond the basic XML document representation, including integrated XPath support, XML schema support, and event-based processing for large documents or streaming documents. It also provides options for building a document representation, which has parallel access through the DOM4J API and the standard DOM interface. It has been in development since the second half of 2000.

To support all of these features, DOM4J uses interfaces and abstract basic class methods. DOM4J uses the collections class in the API extensively, but in many cases it also provides workarounds to allow for better performance or more direct encoding methods. The direct benefit is that while DOM4J has paid the cost of a more complex API, it offers much greater flexibility than jdom.

The goal of DOM4J is the same as jdom when adding flexibility, XPath integration, and the goal of large document processing: Ease of use and intuitive operation for Java developers. It is also committed to becoming a more complete solution than jdom, achieving the goal of essentially addressing all java/xml issues. When this goal is completed, it is less stressed than jdom to prevent incorrect application behavior.

Dom4j is a very, very good Java XML API that features excellent performance, power, and extreme ease of use, and is also an open source software. Now you can see that more and more Java software is using dom4j to read and write XML, especially to mention that even Sun's JAXM is using DOM4J.

2 ... Comparison

1) dom4j performance is the best, even Sun's JAXM is also in use dom4j. Many of the current open source projects use dom4j, such as the famous Hibernate, which also uses DOM4J to read XML configuration files. If portability is not considered, then dom4j is used.

2) Jdom and Dom perform poorly during performance testing, and memory overflows when testing 10M documents. In the case of small documents it is also worth considering DOM and Jdom. Although the developers of Jdom have stated that they expect to focus on performance issues before the full release, there is really no merit in the performance point of view. In addition, Dom is still a very good choice. DOM implementations are widely used in many programming languages. It is also the basis for many other XML-related standards, because it is formally recommended (as opposed to a non-standard Java model), so it may also be needed in some types of projects (such as using the DOM in JavaScript).

3) Sax behaves better, depending on its specific parsing mode-event driven. A sax detects the incoming XML stream, but does not load into memory (of course, some documents are temporarily hidden in memory when the XML stream is read).
3. Basic usage of four kinds of XML operation methods

XML file:



A1234
XX number


B1234
XX Group

1) DOM

Import java.io.*;
Import java.util.*;
Import org.w3c.dom.*;
Import javax.xml.parsers.*;

public class myxmlreader{
public static void Main (String arge[]) {

Long lasting =system.currenttimemillis ();
try{
File F=new file ("Data_10k.xml");
Documentbuilderfactory factory=documentbuilderfactory.newinstance ();
Documentbuilder Builder=factory.newdocumentbuilder ();
Document doc = Builder.parse (f);
NodeList nl = doc.getelementsbytagname ("VALUE");
for (int i=0;i System.out.print ("License plate number:" + doc.getelementsbytagname ("NO"). Item (i). Getfirstchild (). Getnodevalue ());
System.out.println ("Owner's address:" + doc.getelementsbytagname ("ADDR"). Item (i). Getfirstchild (). Getnodevalue ());
}
}catch (Exception e) {
E.printstacktrace ();
}

2) SAX

Import org.xml.sax.*;
Import org.xml.sax.helpers.*;
Import javax.xml.parsers.*;

public class Myxmlreader extends DefaultHandler {

Java.util.Stack tags = new java.util.Stack ();
Public Myxmlreader () {
Super ();
}

public static void Main (String args[]) {
Long lasting = System.currenttimemillis ();
try {
SAXParserFactory SF = Saxparserfactory.newinstance ();
SAXParser sp = Sf.newsaxparser ();
Myxmlreader reader = new Myxmlreader ();
Sp.parse (New InputSource ("Data_10k.xml"), reader);
} catch (Exception e) {
E.printstacktrace ();
}

System.out.println ("Run Time:" + (System.currenttimemillis ()-lasting) + "MS");}
public void characters (char ch[], int start, int length) throws Saxexception {
String tag = (string) tags.peek ();
if (Tag.equals ("NO")) {
System.out.print ("License plate number:" + New String (CH, start, length));
}
if (Tag.equals ("ADDR")) {
SYSTEM.OUT.PRINTLN ("Address:" + New String (CH, start, length));
}
}

public void Startelement (String uri,string localname,string qname,attributes attrs) {
Tags.push (qName);}
}

3) JDOM

Import java.io.*;
Import java.util.*;
Import org.jdom.*;
Import org.jdom.input.*;

public class Myxmlreader {

public static void Main (String arge[]) {
Long lasting = System.currenttimemillis ();
try {
Saxbuilder builder = new Saxbuilder ();
Document doc = builder.build (new File ("Data_10k.xml"));
Element foo = doc.getrootelement ();
List Allchildren = Foo.getchildren ();
for (int i=0;i System.out.print ("License plate Number:" + (Element) allchildren.get (i)). Getchild ("NO"). GetText ());
System.out.println ("Owner's Address:" + (Element) allchildren.get (i)). Getchild ("ADDR"). GetText ());
}
} catch (Exception e) {
E.printstacktrace ();
}

}

4) dom4j

Import java.io.*;
Import java.util.*;
Import org.dom4j.*;
Import org.dom4j.io.*;

public class Myxmlreader {

public static void Main (String arge[]) {
Long lasting = System.currenttimemillis ();
try {
File F = new file ("Data_10k.xml");
Saxreader reader = new Saxreader ();
Document doc = Reader.read (f);
Element root = Doc.getrootelement ();
Element foo;
for (Iterator i = root.elementiterator ("VALUE"); I.hasnext () {
Foo = (Element) i.next ();
System.out.print ("License plate number:" + foo.elementtext ("NO"));
System.out.println ("Owner's address:" + foo.elementtext ("ADDR"));
}
} catch (Exception e) {
E.printstacktrace ();
}
)

Four operations in Java (DOM, sax, Jdom, dom4j) XML in a detailed and comparative way

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.