DOM4J for XML-XML parsing

Source: Internet
Author: User
Dom4j is a simple and flexible open source library. Dom4j was developed independently after it was separated by people who developed JDOM earlier. Unlike JDOM, dom4j uses interfaces and abstract base classes. although Dom4j APIs are more complex, it provides better flexibility than JDOM.


First, why does Dom4j exist?

DOM is too memory-consuming, while SAX can only read XML, rather than add or delete it. As a result, Dom4j is more efficient and supports crud operations.

1. DOM4J introduction
  • Dom4j is a simple and flexible open source library. Dom4j was developed independently after it was separated by people who developed JDOM earlier. Unlike JDOM, dom4j uses interfaces and abstract base classes. although Dom4j APIs are more complex, it provides better flexibility than JDOM.

  • Dom4j is an excellent Java xml api with excellent performance, powerful functionality, and ease of use. Currently, Dom4j is used by many software, such as Hibernate, and JAXP of Sun also uses Dom4j.

  • To use Dom4j for development, you need to download the corresponding jar file of dom4j and import it to the project. Dom4j download

2. DOM4J case

Still use our previous XML file:

 
 <班级>    
  <学生 地址="香港">        
   <名字>
    
Zhou Xiaoxing
           
   <年龄>
    
23
           
   <介绍>
    
Hard work
       
      
  <学生 地址="澳门">        
   <名字>
    
Lin Xiao
           
   <年龄>
    
25
           
   <介绍>
    
Be a good student
       
  
 

Put this document incom.dom4j.testPackage.

To use DOM4J, you must also obtain the entire document.DocumentObject, but this Document object isorg.dom4jPackage.

The Document object obtained in the main method is as follows:

// 1. get a parser SAXReader saxReader = new SAXReader (); // 2. specify the XML file to be parsed, Document document = saxReader. read (new File ("src/com/dom4j/test/myClass. xml "));

Then we can write the corresponding method as needed and call it in the main method.

[1] specify to read an element (read the information of the first student)

Public static void read (Document document) {// Obtain the root Element root = document. getRootElement (); // root. elements ("student"): extracts all student elements under root. // root. element ("student"): obtains the first student Element element student = root under root. element ("student"); // retrieves the attribute String address = student. attributeValue ("address"); // retrieves the value of each subnode. String name = student. element ("name "). getText (); String age = student. element ("age "). getText (); String intro = student. element ("Introduction "). getText (); System. out. println (address); System. out. println (name); System. out. println (age); System. out. println (intro );}

[2] add element: add a student information to XML document

Public static void add (Document document) throws Exception {// first create a student node object Element student = incluenthelper. createElement ("student"); Element name = incluenthelper. createElement ("name"); name. setText ("Xiaoqiang"); Element age = incluenthelper. createElement ("age"); age. setText ("22"); Element intro = incluenthelper. createElement ("Introduction"); intro. setText ("being a good student"); // add the three child elements to student under the student node. add (name); student. add (age); student. add (intro); // add attributes to students. addAttribute ("address", "Dali"); // add the student node to the document under the root node. getRootElement (). add (student); // update the xml file. the output will contain Chinese garbled characters. use OutputFormat output = OutputFormat. createPrettyPrint (); // sets the output encoding to UTF-8 output. setEncoding ("UTF-8"); // you must use FileOutputStream to output byte streams. you cannot use FileWriter, otherwise, the XMLWriter xmlWriter = new XMLWriter (new FileOutputStream ("src/com/dom4j/test/myClass. xml "), output); xmlWriter. write (document); xmlWriter. close ();}

To add a student to an XML Document, you also need to write the Document object in the memory to the corresponding file. otherwise, all the operations are only performed in the memory and will not be output to the file, this is similar to DOM.
We can still write this updated code as a separate method, as shown below:

Public static void update (Document document) throws Exception {// update the xml file. Chinese garbled characters are directly output. use OutputFormat output = OutputFormat. createPrettyPrint (); // sets the output encoding to UTF-8 output. setEncoding ("UTF-8"); XMLWriter xmlWriter = new XMLWriter (new FileOutputStream ("src/com/dom4j/test/myClass. xml "), output); xmlWriter. write (document); xmlWriter. close ();}

[3] add an element to a specified position

Public static void addByIndex (Document document) throws Exception {// create an Element newStu = incluenthelper. createElement ("student"); newStu. setText ("Wang Xiaoming"); // obtain the list of all students allStudent = document. getRootElement (). elements ("student"); allStudent. add (1, newStu); update (document );}

In fact, it is obtained directly.ListAnd then update it. HereListYesjava.utilPackageList

[4] Deleting an element or its attributes
Deleting an element is similar to DOM. it is deleted through the corresponding parent node. For example, we want to delete the first student node:

Public static void delete (Document document) throws Exception {// locate the Element student = document. getRootElement (). element ("student"); // deletes an attribute of an element, student. remove (student. attribute ("address"); // delete the node student through the parent node. getParent (). remove (student); update (document );}

[5] updating elements
For example, we want to add the age of all students to 1 and change the address attribute of all students to the United States:

Public static void updateAgeAndAddress (Document document) throws Exception {Element root = document. getRootElement (); List
 
  
List = root. elements (); for (Element element: list) {// update attribute element. addAttribute ("address", "USA"); // update the value of the age subnode Element e_age = element. element ("age"); int age = Integer. parseInt (e_age.getTextTrim (); e_age.setText (String. valueOf (age + 1);} update (document );}
 

First, why does Dom4j exist?

DOM is too memory-consuming, while SAX can only read XML, rather than add or delete it. As a result, Dom4j is more efficient and supports crud operations.

1. DOM4J introduction
  • Dom4j is a simple and flexible open source library. Dom4j was developed independently after it was separated by people who developed JDOM earlier. Unlike JDOM, dom4j uses interfaces and abstract base classes. although Dom4j APIs are more complex, it provides better flexibility than JDOM.

  • Dom4j is an excellent Java xml api with excellent performance, powerful functionality, and ease of use. Currently, Dom4j is used by many software, such as Hibernate, and JAXP of Sun also uses Dom4j.

  • To use Dom4j for development, you need to download the corresponding jar file of dom4j and import it to the project. Dom4j download

2. DOM4J case

Still use our previous XML file:

 
 <班级>    
  <学生 地址="香港">        
   <名字>
    
Zhou Xiaoxing
           
   <年龄>
    
23
           
   <介绍>
    
Hard work
       
      
  <学生 地址="澳门">        
   <名字>
    
Lin Xiao
           
   <年龄>
    
25
           
   <介绍>
    
Be a good student
       
  
 

Put this document incom.dom4j.testPackage.

To use DOM4J, you must also obtain the entire document.DocumentObject, but this Document object isorg.dom4jPackage.

The Document object obtained in the main method is as follows:

// 1. get a parser SAXReader saxReader = new SAXReader (); // 2. specify the XML file to be parsed, Document document = saxReader. read (new File ("src/com/dom4j/test/myClass. xml "));

Then we can write the corresponding method as needed and call it in the main method.

[1] specify to read an element (read the information of the first student)

Public static void read (Document document) {// Obtain the root Element root = document. getRootElement (); // root. elements ("student"): extracts all student elements under root. // root. element ("student"): obtains the first student Element element student = root under root. element ("student"); // retrieves the attribute String address = student. attributeValue ("address"); // retrieves the value of each subnode. String name = student. element ("name "). getText (); String age = student. element ("age "). getText (); String intro = student. element ("Introduction "). getText (); System. out. println (address); System. out. println (name); System. out. println (age); System. out. println (intro );}

[2] add element: add a student information to XML document

Public static void add (Document document) throws Exception {// first create a student node object Element student = incluenthelper. createElement ("student"); Element name = incluenthelper. createElement ("name"); name. setText ("Xiaoqiang"); Element age = incluenthelper. createElement ("age"); age. setText ("22"); Element intro = incluenthelper. createElement ("Introduction"); intro. setText ("being a good student"); // add the three child elements to student under the student node. add (name); student. add (age); student. add (intro); // add attributes to students. addAttribute ("address", "Dali"); // add the student node to the document under the root node. getRootElement (). add (student); // update the xml file. the output will contain Chinese garbled characters. use OutputFormat output = OutputFormat. createPrettyPrint (); // sets the output encoding to UTF-8 output. setEncoding ("UTF-8"); // you must use FileOutputStream to output byte streams. you cannot use FileWriter, otherwise, the XMLWriter xmlWriter = new XMLWriter (new FileOutputStream ("src/com/dom4j/test/myClass. xml "), output); xmlWriter. write (document); xmlWriter. close ();}

To add a student to an XML Document, you also need to write the Document object in the memory to the corresponding file. otherwise, all the operations are only performed in the memory and will not be output to the file, this is similar to DOM.
We can still write this updated code as a separate method, as shown below:

Public static void update (Document document) throws Exception {// update the xml file. Chinese garbled characters are directly output. use OutputFormat output = OutputFormat. createPrettyPrint (); // sets the output encoding to UTF-8 output. setEncoding ("UTF-8"); XMLWriter xmlWriter = new XMLWriter (new FileOutputStream ("src/com/dom4j/test/myClass. xml "), output); xmlWriter. write (document); xmlWriter. close ();}

[3] add an element to a specified position

Public static void addByIndex (Document document) throws Exception {// create an Element newStu = incluenthelper. createElement ("student"); newStu. setText ("Wang Xiaoming"); // obtain the list of all students allStudent = document. getRootElement (). elements ("student"); allStudent. add (1, newStu); update (document );}

In fact, it is obtained directly.ListAnd then update it. HereListYesjava.utilPackageList

[4] Deleting an element or its attributes
Deleting an element is similar to DOM. it is deleted through the corresponding parent node. For example, we want to delete the first student node:

Public static void delete (Document document) throws Exception {// locate the Element student = document. getRootElement (). element ("student"); // deletes an attribute of an element, student. remove (student. attribute ("address"); // delete the node student through the parent node. getParent (). remove (student); update (document );}

[5] updating elements
For example, we want to add the age of all students to 1 and change the address attribute of all students to the United States:

Public static void updateAgeAndAddress (Document document) throws Exception {Element root = document. getRootElement (); List
 
  
List = root. elements (); for (Element element: list) {// update attribute element. addAttribute ("address", "USA"); // update the value of the age subnode Element e_age = element. element ("age"); int age = Integer. parseInt (e_age.getTextTrim (); e_age.setText (String. valueOf (age + 1);} update (document );}
 

The above is the DOM4J XML-XML parsing content, more relevant content please pay attention to PHP Chinese network (www.php1.cn )!

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.