[Path to Java Development] (12) Parse XML documents using JDOM and DOM4J

Source: Internet
Author: User

[Path to Java Development] (12) Parse XML documents using JDOM and DOM4J
1. parse XML documents using JDOM1.1 Introduction JDOM is an open-source project. Based on the tree structure, JDOM uses JAVA-only technology to parse, generate, serialize, and perform multiple operations on XML documents. JDOM directly serves JAVA programming. It effectively integrates the functions of SAX and DOM by taking advantage of the many features of the more powerful JAVA language (method overloading, set concepts, and ing. In terms of use design, try to hide the complexity of the original XML Process. Using JDOM to process XML documents is easy and simple. JDOM help documentation: http://www.jdom.org/docs/apidocs/ Jar package: Click to open the link 1.2 parsing step (1) create a SAXBuilder object

 
SAXBuilder saxBuilder = new SAXBuilder();(2) create an input stream object and load the XML document to the input stream. 
 
FileInputStream inputStream = new FileInputStream("D:\\bookstore.xml");(3) load the input stream to saxBuilder by using the build method of the saxBuilder object (note: the Document referenced package is org. jdom2.Document ;) 
 
Document document = saxBuilder.build(inputStream);(4) Get the root node of the XML document through the document Object 
 
Element rootElement = document.getRootElement();(5) obtain the subnode set under the root node based on the Root Node 
 
List  bookList = rootElement.getChildren(); (6) retrieving attribute node sets based on nodes 
 
List attrList = book.getAttributes();(7) obtain the node name and Value Based on the node (element node or attribute node) 
 
// Attribute name 
node.getName(); 
// Attribute Value 
node.getValue();1.3 Main method (1) return the document's root node public Element getRootElement () 
 
// Document is a Document object 
Element rootElement = document.getRootElement();(2) return the public java. util. List of all subnodes of the node.  GetChildren ()  
 
// The rootElement is an Element object. 
List  bookList = rootElement.getChildren(); (3) return the public java. util. List getAttributes () set of all attribute nodes of the node () 
 
// Book is an Element object 
List attrList = book.getAttributes()(4) return the public Element getChild (java. lang. String cname) of the subnode Based on the subnode name) 
 
Element titleElement = book.getChild("title");(5) return the node name public java. lang. String getName () 
 
// TitleElement is the title node. 
titleElement.getName();(6) return the node values public java. lang. String getValue (), 
 
titleElement.getValue()The DOM method getNodeValue () returns null for element nodes. Different from DOM, JDOM returns the text value corresponding to the node, whether it is an attribute node or an element node. 
 
Scott MeyersFor this node, DOM getNodeValue () returns null, and JDOM getValue () returns "Scott Meyers ". 
1.3 specific instance
 
package com.qunar.xml;  
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.util.List;  
import org.jdom2.Attribute; 
import org.jdom2.Document; 
import org.jdom2.Element; 
import org.jdom2.JDOMException; 
import org.jdom2.input.SAXBuilder;  
/** 
* Parse XML documents using JDOM 
* @author sjf0115 
* 
*/ 
public class JDOMXMLCode {  
public static void main(String[] args) { 
try { 
// Create a SAXBuilder object 
SAXBuilder saxBuilder = new SAXBuilder(); 
// Create an input stream object and load the XML document to the input stream 
FileInputStream inputStream = new FileInputStream("D:\\bookstore.xml"); 
// Load the input stream to saxBuilder using the build method of the saxBuilder object 
Document document = saxBuilder.build(inputStream); 
// Get the root node of the XML document through the document Object 
Element rootElement = document.getRootElement(); 
// Obtain the subnode set under the root node based on the Root Node 
List  bookList = rootElement.getChildren();  
// Traverse subnodes 
for (Element book : bookList) { 
System. out. println ("starting to parse a book ...");  
// Parse attributes 
List attrList = book.getAttributes(); 
for (Attribute attribute : attrList) { 
// Attribute name 
System.out.print("---" + attribute.getName() + ":"); 
// Attribute Value 
System.out.println(attribute.getValue()); 
}//for  
// Obtain the subnode under the book Node 
List  bookChildren = book.getChildren();  
for (Element bookChild : bookChildren) { 
// Node name 
System.out.print("------" + bookChild.getName() + ":"); 
// Node Value 
System.out.println(bookChild.getValue()); 
}//for  
System. out. println ("End parsing a book ..."); 
}//for 
} catch (FileNotFoundException e) { 
e.printStackTrace(); 
} catch (JDOMException e) { 
e.printStackTrace(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
} 
Running result: 

Start parsing a book... --- category: Java ------ title: Java multi-thread programming core technology ------ author: Gao Hongyan ------ year: 2015 ------ price: 69.00 end parsing a book... start parsing a book... --- category: C ++ ------ title: Valid tive C ++: 55 Specific Ways to Improve Your Programs and Designs ------ author: Scott Meyers ------ year: 2006 ------ price: 58.00 end parsing a book... start parsing a book... --- category: Web ------ title: Learning XML ------ author: Erik T. ray ------ year: 2016 ------ price: 39.95 end parsing a book...
2. DOM4J parses XML documents2.1 Introduction DOM4J is a Java xml api, similar to JDOM, used to read and write XML files. DOM4J is a very good JavaXML API with excellent performance, powerful functionality, and extremely easy to use features. It is also an open source software that can be found on SourceForge. Now we can see that more and more Java software are using DOM4J to read and write XML. It is particularly worth mentioning that Sun's JAXM is also using DOM4J. This is a required jar package. Hibernate also uses it to read and write configuration files. Jar package: click open link 2.2 to parse (1) create a SAXReader object
 
SAXReader saxReader = new SAXReader();(2) Use the read method of the SaxReader object to load the XML Document and obtain the Document object. 
 
Document document = saxReader.read(new File("D:\\bookstore.xml"));(3) Get the root node through the Document Object 
 
Element bookstore = document.getRootElement();(4) obtain the iterator through the elementIterator method of the Element Object 
 
Iterator iterator = bookstore.elementIterator();(5) traverse the iterator to get the root node Information 
 
while (iterator.hasNext()) { 
// Obtain the next subnode 
Element book = (Element)iterator.next(); 
}(6) Get the attribute name and attribute value of the attribute node 
 
// Obtain the attribute node set of the book 
List bookAttr = book.attributes(); 
// Traverse the book attribute node 
for (Attribute attribute : bookAttr) { 
// Obtain the attribute name and attribute value of the property node of the book. 
System.out.println("name:" + attribute.getName() + " value:" + attribute.getValue()); 
}//for(7) obtain the node name and the corresponding text value of the element node. 
 
Iterator ite = book.elementIterator(); 
// Traverse the child nodes of the book Node 
while(ite.hasNext()){ 
// Subnode of the book Node 
Element bookChild = (Element)ite.next(); 
System.out.println("name:" + bookChild.getName() + " value:" + bookChild.getStringValue()); 
//System.out.println("name:" + bookChild.getName() + " value:" + bookChild.getText()); 
}//while2.3 case studies 
 
package com.qunar.xml;  
import java.io.File; 
import java.util.Iterator; 
import java.util.List;  
import org.dom4j.Attribute; 
import org.dom4j.Document; 
import org.dom4j.DocumentException; 
import org.dom4j.Element; 
import org.dom4j.io.SAXReader;  
public class DOM4JXMLCode {  
public static void main(String[] args) { 
try { 
// Create a SAXReader object 
SAXReader saxReader = new SAXReader(); 
// Load the XML Document using the read method of the SaxReader object to obtain the Document Object 
Document document = saxReader.read(new File("D:\\bookstore.xml")); 
// Get the root node through the Document Object 
Element bookstore = document.getRootElement(); 
// Obtain the iterator through the elementIterator method of the Element Object 
Iterator iterator = bookstore.elementIterator(); 
// Traverse the child nodes of the Root Node 
while (iterator.hasNext()) { 
System. out. println ("starting to parse a book ..."); 
// Obtain the next Element Node 
Element book = (Element)iterator.next(); 
// Obtain the attribute node set of the book 
List bookAttr = book.attributes(); 
// Traverse the book attribute node 
for (Attribute attribute : bookAttr) { 
// Obtain the attribute name and attribute value of the property node of the book. 
System.out.println("name:" + attribute.getName() + " value:" + attribute.getValue()); 
}//for 
Iterator ite = book.elementIterator(); 
// Traverse the child nodes of the book Node 
while(ite.hasNext()){ 
// Subnode of the book Node 
Element bookChild = (Element)ite.next(); 
System.out.println("name:" + bookChild.getName() + " value:" + bookChild.getStringValue()); 
//System.out.println("name:" + bookChild.getName() + " value:" + bookChild.getText()); 
}//while 
System. out. println ("End parsing a book ..."); 
} 
} catch (DocumentException e) { 
e.printStackTrace(); 
} 
} 
} 
Running result: 

Start parsing a book... name: category value: Javaname: title value: Java multi-thread programming core technology name: author value: Gao Hongyan name: year value: 2015 name: price value: 69.00 end parsing a book... start parsing a book... name: category value: C ++ name: title value: Valid tive C ++: 55 Specific Ways to Improve Your Programs and Designsname: author value: Scott Meyersname: year value: 2006 name: price value: 58.00 end parsing a book... start parsing a book... name: category value: Webname: title value: Learning XMLname: author value: Erik T. rayname: year value: 2016 name: price value: 39.95 end parsing a book...
 

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.