Home Java javaTutorial Detailed introduction to comparison code examples of four ways to operate xml in java

Detailed introduction to comparison code examples of four ways to operate xml in java

Mar 21, 2017 am 10:52 AM
java xml operate

This article mainly introduces four ways to operate xml in java and compares and analyzes them. Has very good reference value. Let’s take a look at it with the editor

1) DOM (JAXP Crimson parser)

DOM represents XML documents in a platform- and language-independent way Official W3C standard. 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, the DOM is considered tree-based or object-based. DOM, and tree-based processing in general, has 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 structures. It also allows navigation up and down the tree at any time, rather than a one-time process like SAX. DOM is also much simpler to use.

2) SAX

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 programming is easy. 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.

3) JDOM

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.

4) DOM4J

Although DOM4J represents a completely independent development result, initially, it was an intelligent fork 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 processing of 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.

2… … Comparison

1) DOM4J has the best performance, even Sun’s JAXM is also using DOM4J. Currently, many open source projects use DOM4J extensively. For example, the famous Hibernate also uses DOM4J to read XML. Configuration file. If portability is not considered, then use DOM4J.

2) JDOM and DOM performed poorly during performance testing, and memory overflowed when testing 10M documents. 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 in Javascript uses DOM).

3) SAX performs better, which depends on its specific parsing method - event driver . 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).

3. Basic usage of the four xml operation methodsMethod

xml file:

<?xml version="1.0" encoding="GB2312"?> 
<RESULT> 
<VALUE> 
   <NO>A1234</NO> 
   <ADDR>四川省XX县XX镇XX路X段XX号</ADDR> 
</VALUE> 
<VALUE> 
   <NO>B1234</NO> 
   <ADDR>四川省XX市XX乡XX村XX组</ADDR> 
</VALUE> 
</RESULT>
Copy after login

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<nl.getLength();i++){ 
    System.out.print("车牌号码:" + doc.getElementsByTagName("NO").item(i).getFirstChild().getNodeValue()); 
    System.out.println("车主地址:" + doc.getElementsByTagName("ADDR").item(i).getFirstChild().getNodeValue()); 
   } 
  }catch(Exception e){ 
   e.printStackTrace(); 
}
Copy after login

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("运行时间:" + (System.currentTimeMillis() - lasting) + "毫秒");} 
  public void characters(char ch[], int start, int length) throws SAXException { 
  String tag = (String) tags.peek(); 
  if (tag.equals("NO")) { 
   System.out.print("车牌号码:" + new String(ch, start, length)); 
} 
if (tag.equals("ADDR")) { 
  System.out.println("地址:" + new String(ch, start, length)); 
} 
} 
  public void startElement(String uri,String localName,String qName,Attributes attrs) { 
  tags.push(qName);} 
}
Copy after login

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<allChildren.size();i++) { 
    System.out.print("车牌号码:" + ((Element)allChildren.get(i)).getChild("NO").getText()); 
    System.out.println("车主地址:" + ((Element)allChildren.get(i)).getChild("ADDR").getText()); 
   } 
  } catch (Exception e) { 
   e.printStackTrace(); 
} 
}
Copy after login

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("车牌号码:" + foo.elementText("NO")); 
    System.out.println("车主地址:" + foo.elementText("ADDR")); 
   } 
  } catch (Exception e) { 
   e.printStackTrace(); 
}
Copy after login

The above is the detailed content of Detailed introduction to comparison code examples of four ways to operate xml in java. For more information, please follow other related articles on the PHP Chinese website!

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

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

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)

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles