Use dom4j in java to parse xml (sample code)

Source: Internet
Author: User
In view of the current trend, let's talk about the basic usage of Dom4j, without complex operations such as recursion. Dom4j has a lot of usage, and the examples on the official website are a little obscure. I will not write it here, although Java already has the Dom and Sax standard parsing methods.

But it is not easy to operate. for a beginner like me, some of the code is actually disgusting.

To this end, great third-party developers have developed tools such as Jdom and Dom4j.

In view of the current trend, let's talk about the basic usage of Dom4j, and do not involve complex operations such as recursion.

Dom4j is widely used. the examples on the official website are so obscure that I will not write them here.

First, we need to create an xml document before parsing it.

Xml document:

  
     
         
   Harry Potter       J K. Rowling    
      
         
   Learning XML       Erik T. Ray    
   
 

Example 1: parse xml using List

Import java. io. file; import java. util. list; import org. dom4j. attribute; import org. dom4j. document; import org. dom4j. element; import org. dom4j. io. SAXReader; public class Demo {public static void main (String [] args) throws Exception {SAXReader reader = new SAXReader (); File file = new File ("books. xml "); Document document = reader. read (file); Element root = document. getRootElement (); List
 
  
ChildElements = root. elements (); for (Element child: childElements) {// unknown attribute name/* List attributeList = child. attributes (); for (Attribute attr: attributeList) {System. out. println (attr. getName () + ":" + attr. getValue ();} * // System with a known attribute name. out. println ("id:" + child. attributeValue ("id"); // when the sub-element name is unknown/* List
  
   
ElementList = child. elements (); for (Element ele: elementList) {System. out. println (ele. getName () + ":" + ele. getText ();} System. out. println (); * // when the sub-element name is known, System. out. println ("title" + child. elementText ("title"); System. out. println ("author" + child. elementText ("author"); // This line exists for the purpose of formatting. out. println ();}}}
  
 

Example 2: Use the Iterator to parse xml

Import java. io. file; import java. util. iterator; import org. dom4j. attribute; import org. dom4j. document; import org. dom4j. element; import org. dom4j. io. SAXReader; public class Demo {public static void main (String [] args) throws Exception {SAXReader reader = new SAXReader (); Document document = reader. read (new File ("books. xml "); Element root = document. getRootElement (); Iterator it = root. elementIterator (); while (it. hasNext () {Element element = (Element) it. next (); // when the attribute name is unknown/* Iterator attrIt = element. attributeIterator (); while (attrIt. hasNext () {Attribute a = (Attribute) attrIt. next (); System. out. println (. getValue ();} * // System with a known attribute name. out. println ("id:" + element. attributeValue ("id"); // if the element name is unknown,/* Iterator eleIt = element. elementIterator (); while (eleIt. hasNext () {Element e = (Element) eleIt. next (); System. out. println (e. getName () + ":" + e. getText ();} System. out. println (); * // if the element name is known, System. out. println ("title:" + element. elementText ("title"); System. out. println ("author:" + element. elementText ("author"); System. out. println ();}}}

Running result:

Example 3: Create an xml document and output it to a file

Import java. io. file; import java. io. fileOutputStream; import org. dom4j. document; import org. dom4j. export enthelper; import org. dom4j. element; import org. dom4j. io. outputFormat; import org. dom4j. io. XMLWriter; public class Demo {public static void main (String [] args) throws Exception {Document doc = DocumentHelper. createDocument (); // add the root node Element books = doc. addElement ("books"); // add the sub-Element book1 = books. addElement ("book"); Element title1 = book1.addElement ("title"); Element author1 = book1.addElement ("author"); Element book2 = books. addElement ("book"); Element title2 = book2.addElement ("title"); Element author2 = book2.addElement ("author"); // add a property book1.addattriement ("id ", "001"); // add title1.setText ("Harry Potter") for the element; author1.setText ("j k. rowling "); book2.addAttribute (" id "," 002 "); title2.setText (" Learning XML "); author2.setText (" Erik T. ray "); // instantiate the output format object OutputFormat format = OutputFormat. createPrettyPrint (); // sets the output encoding format. setEncoding ("UTF-8"); // create the File object File = new file ("D:" + File. separator + "books. xml "); // Generate the XMLWriter object. the parameters in the constructor are the file stream to be output and the format XMLWriter writer = new XMLWriter (new FileOutputStream (file), format ); // start writing. the write method contains the Document Object writer created above. write (doc );}}

Running result:

For more articles about using dom4j to parse xml (sample code) in java, please follow the PHP Chinese network!

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.