_JSP programming of four XML parsing techniques in Java

Source: Internet
Author: User
Tags gettext xpath

In peacetime work, it is inevitable to encounter the XML as a data storage format. In the face of the current variety of solutions, which is the best for us? In this article, I'm going to do an incomplete evaluation of these four mainstream scenarios, just testing for traversing XML, because traversing XML is the most used work (at least I think).

Preparatory

   test Environment:

AMD Poison Dragon 1.4G OC 1.5G, 256M DDR333, Windows2000 Server SP4, Sun JDK 1.4.1+eclipse 2.1+resin 2.1.8, tested in Debug mode.

The XML file format is as follows:

<?xml version= "1.0" encoding= "GB2312"?
<RESULT>
<VALUE>
<NO> A1234 </NO>
<ADDR> xx xx road x section xx, xx County, Sichuan province </ADDR>
</VALUE>
<VALUE>
<NO> B1234 </NO>
<ADDR> xx Xiang xx village xx Group, xx City, Sichuan province </ADDR>
</VALUE>
</RESULT>

   test Method:

Using the JSP-side call Bean (as for why the use of JSP to invoke, please refer to: http://blog.csdn.net/rosen/archive/2004/10/15/138324.aspx), so that each solution to resolve the 10K, 100K, 1000K, 10000K XML file that calculates its elapsed time (in milliseconds).

JSP file:

<%@ page contenttype= "text/html; charset=gb2312 "%>
<%@ page import= "com.test.*"%>

<body>
<%
String args[]={""};
Myxmlreader.main (args);
%>
</body>

Test

The first exit is DOM (JAXP Crimson Parser)

DOM is the official consortium standard for representing XML documents in a platform-and language-independent way. A DOM is a collection of nodes or pieces of information organized in a hierarchical structure. This hierarchy allows developers to find specific information in the tree. Parsing the structure usually requires loading the entire document and the construction 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, it can be modified 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-time process like SAX. DOM is much simpler to use.

On the other hand, for exceptionally large documents, parsing and loading the entire document can be slow and resource-intensive, so it would be better to use other means to process such data. These event-based models, such as SAX.

Bean file:

Package com.test;

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<nl.getlength (); i++) {
System.out.print ("License plate number:" + doc.getelementsbytagname ("NO"). Item (i). Getfirstchild (). Getnodevalue ());
System.out.println ("Owner address:" + doc.getelementsbytagname ("ADDR"). Item (i)-getfirstchild (). Getnodevalue ());
}
}catch (Exception e) {
E.printstacktrace ();
}
System.out.println ("Run Time:" + (System.currenttimemillis ()-lasting) + "MS");
}
}


10k Consumption Time: 265 203 219 172
100k consumption Time: 9172 9016 8891 9000
1000k consumption time: 691719 675407 708375 739656
10000k Consumption time: OutOfMemoryError

Then there's SAX.

The advantages of this kind of processing are very similar to the advantages of streaming media. Analysis can begin immediately, rather than wait for all data to be processed. Also, because an application checks data only when it reads data, it does not need to store the data in memory. This is a great advantage for large documents. In fact, an application doesn't even have to parse the entire document; it can stop parsing when a condition is satisfied. In general, SAX is much faster than its replacement DOM.

Select DOM or SAX?

Choosing a DOM or SAX parsing model is a very important design decision for developers who need to write their own code to work with XML documents.

DOM uses a tree-structured approach to accessing XML documents, while SAX uses the event model.

The DOM parser converts an XML document into a tree containing its contents, and can traverse the tree. The advantage of using the DOM parsing model is that it is easy to program, the developer only needs to invoke the build instructions, and then use the navigation APIs to access the required tree nodes to complete the task. You can easily add and modify elements in the tree. However, because of the need to process the entire XML document with the DOM parser, the performance and memory requirements are high, especially when you encounter a large XML file. Because of its traversal capabilities, DOM parsers are often used in services where XML documents require frequent changes.

The SAX parser employs an event-based model that triggers a series 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 typically requires less memory because it lets developers decide which tag they want to handle. Especially when developers only need to work with some of the data contained in the document, SAX has a better ability to expand. But coding is difficult when using a SAX parser, and it is difficult to access multiple different data in the same document at the same time.

Bean file:

Package com.test;
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);
}
}

10k Consumption Time: 110 47 109 78
100k consumption Time: 344 406 375 422
1000k consumption time: 3234 3281 3688 3312
10000k consumption time: 32578 34313 31797 31890 30328

And then the JDOM http://www.jdom.org/.

The goal of JDOM is to become a Java-specific document model that simplifies interaction with XML and is faster than using DOM. Because it is the first Java-specific model, JDOM has been vigorously promoted and promoted. is considering using the Java specification Request JSR-102 to eventually use it as a "java standard extension". JDOM has been developed since the beginning of the 2000.

There are two main differences between JDOM and DOM. First, JDOM uses only specific classes instead of interfaces. This simplifies the API in some ways, but it also limits flexibility. Second, the API uses a lot of collections classes, simplifying the use of Java developers who are already familiar with these classes.

The JDOM document declares that its purpose is "to use 20% (or less) energy to solve 80% (or more) java/xml problems" (assuming 20% according to the learning curve). JDOM is of course useful for most java/xml applications, and most developers find APIs much easier to understand than DOM. JDOM also includes a fairly extensive review of program behavior to prevent users from doing anything that is meaningless in XML. However, it still requires you to fully understand XML in order to do something beyond the basics (or even to understand some cases of errors). This may be more meaningful than learning a DOM or JDOM interface.

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

Bean file:

Package com.test;

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<allchildren.size (); 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 ();
}
System.out.println ("Run Time:" + (System.currenttimemillis ()-lasting) + "MS");
}
}

10k Consumption Time: 125 62 187 94
100k consumption Time: 704 625 640 766
1000k consumption time: 27984 30750 27859 30656
10000k Consumption time: OutOfMemoryError

And finally, dom4j http://dom4j.sourceforge.net/.

Although DOM4J represents a completely independent development result, it was initially an intelligent branch of JDOM. It incorporates a number of features beyond the representation of basic XML documents, including integrated XPath support, XML Schema support, and event-based processing for large documents or streaming documents. It also provides the option to build the document representation, which has parallel access through the dom4j API and the standard DOM interface. It has been under 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 heavily, but in many cases it also provides workarounds to allow for better performance or more direct coding methods. The immediate benefit is that although DOM4J has paid the cost of more complex APIs, it provides much greater flexibility than JDOM.

When adding flexibility, XPath integration, and goals for large document processing, DOM4J's goal is the same as JDOM: ease of use and intuitive operation for Java developers. It is also dedicated 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 improper application behavior.

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

Bean file:

Package com.test;

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 address:" + foo.elementtext ("ADDR"));
}
catch (Exception e) {
E.printstacktrace ();
}
System.out.println ("Run Time:" + (System.currenttimemillis ()-lasting) + "MS");
}
}

10k Consumption Time: 109 78 109 31
100k consumption Time: 297 359 172 312
1000k consumption time: 2281 2359 2344 2469
10000k consumption time: 20938 19922 20031 21078

JDOM and DOM perform poorly during performance testing, and memory overflows when testing 10M documents. It is also worth considering using DOM and JDOM in small document situations. While JDOM developers have indicated that they expect to focus on performance issues before the formal release, it does not have a merit to recommend from a performance standpoint. In addition, DOM is still a very good choice. DOM implementations are widely used in a variety of programming languages. It is also the basis for many other XML-related standards because it is officially recommended by the Consortium (as opposed to a non-standard Java model), so it may be needed in some types of projects (such as using DOM in JavaScript).

Sax behaves better, depending on its specific parsing style. A SAX detects the incoming XML stream, but it is not loaded into memory (of course, when the XML stream is read, some of the documents are temporarily hidden in memory).

There is no doubt that DOM4J is the winner of this test, and many open source projects now use dom4j, such as the famous Hibernate also use dom4j to read XML configuration files. If you do not consider portability, then use DOM4J Bar!

Related Article

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.