DOM4J parsing sample code for XML parsing

Source: Internet
Author: User
The company's APP has been there for a long time. the previous interface results are processed in XML format. in the project, there are various ways for each person to process XML, and there is no unified processing method, therefore, it is very distressing to use it. Therefore, every time the project owner is in development, in order to save his time, he does not study the XML Parsing method of other personnel, as long as he encounters XML, the author uses DOM4J for parsing. The company's APP has been there for a long time. the previous interface results are processed in XML format. in the project, there are various ways for each person to process XML, and there is no unified processing method, therefore, it is very distressing to use it. Therefore, every time the project owner is in development, in order to save his time, he does not study the XML Parsing method of other personnel, as long as he encounters XML, the author uses DOM4J for parsing.

There are many ways to parse XML, such as DOM, SAX, and JDOM. I will not talk about the usage and principle here (ps: The author does not know the usage and principle ). This article mainly describes the simple operations and usage of DOM4J.

DOM4J introduction

Dom4j is a Java xml api and a jdom upgrade product 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. its performance exceeds sun's official dom technology, it is also an open-source software that can be found on SourceForge.

Dom4j is an easy-to-use and open-source library for XML, XPath, and XSLT. It is applied to the Java platform. it adopts the Java collection framework and fully supports DOM, SAX, and JAXP.

Here is a simple example to introduce the usage of DOM4J.

Note: To use DOM4J to parse XML, you must introduce the DOM4J jar package in the project.

XML file

     
  
   
Image 1
      
  
   
Image 2
      
  
   
Image 3
  
 

DOM4J usage details
Step 1: load the xml file

There are two main ways to load xml:

1. directly load the path of the file

2. load xml in the string format (this method is mainly used in the results returned by the server)

1.1 directly load the file path

   SAXReader reader = new SAXReader();        Document document = null;        try {            document = reader.read(new File("E://CZBK//day01//caseUp.xml"));        } catch (DocumentException e) {            e.printStackTrace();        }

1.2. load xml in string form

SAXReader reader = new SAXReader (); Document document = null; try {// result is the string to be parsed // The parsed string needs to be converted into a stream, you can specify the conversion character encoding document = reader. read (new ByteArrayInputStream (result. getBytes ("UTF-8");} catch (incluentexception e) {e. printStackTrace ();}

Step 2: parse XML

Before parsing XML, let's first introduce the structure of XML. it is helpful to understand the following four problems.

What is a node )? What is an element )? What is attribute )? What is a text value )?

Nodes: "Response" and "Media" are called nodes.

Element: ends with a complete tag and contains the entire element content. For example: Image 1

Attribute: the attribute value of a node, which is added to the content of the node. For example, T = '000000' T1 = '6' TaskID = '000000' MediaNum = '3' Result = '1' Desc = 'query successful! '

Text value: "Image 1" is called a text value.

In a project, operations are performed on elements, attributes, and text values. Therefore, you can master the value methods of these three parts and understand XML parsing.

2.1 obtain the root node

// Obtain the entire document Element rootElement = document. getRootElement ();

RootElement contains the content of the entire xml document, that is, all the content contained in the Response tag.

2.2. get the property value of the Response node

// Obtain the value of the Result attribute of the Response node String responseResult = rootElement. attributeValue ("Result ");

2.3. obtain Media elements

// Obtain the first Media Element element mediaElement = rootElement. Element ("Media"); // Obtain all Media elements List allMeidaElements = rootElement. elements ("Media ");

2.4. get the Media property value

// Obtain the Name attribute value of the first Media element String mediaName = mediaElement. attributeValue ("Name"); // traverses the Name attribute values of all Media elements for (int I = 0; I <allMeidaElements. size (); I ++) {Element element = (Element) allMeidaElements. get (I); String name = element. attributeValue ("Name ");}

2.5. obtain the text value of the Media tag.

// Obtain the text value of the first Meida element String value = mediaElement. getText ();

Complete Code

Import java. io. file; import java. util. list; import org. dom4j. document; import org. dom4j. extends entexception; import org. dom4j. element; import org. dom4j. io. SAXReader; public class Textxml {public void xml () {SAXReader reader = new SAXReader (); Document document = null; try {document = reader. read (new File ("E: // CZBK // day01 // caseUp. xml ");} catch (incluentexception e) {e. printStackTrace ();} // Obtain the entire document Element rootElement = document. getRootElement (); System. out. println ("entire document:" + rootElement. asXML (); // get the Result attribute value of the Response node String responseResult = rootElement. attributeValue ("Result"); System. out. println ("Response node Result property value:" + responseResult); // gets the first Media Element mediaElement = rootElement. element ("Media"); System. out. println ("First Media element:" + mediaElement. asXML (); // Obtain all Media element List allMeidaElements = rootElement. elements ("Media"); // Obtain the Name attribute value of the first Media element String mediaName = mediaElement. attributeValue ("Name"); System. out. println ("Name attribute value of the first Media element:" + mediaName); // traverses the Name attribute value of all Media elements for (int I = 0; I <allMeidaElements. size (); I ++) {Element element = (Element) allMeidaElements. get (I); String name = element. attributeValue ("Name");} // Obtain the text value of the first Meida element String value = mediaElement. getText (); System. out. println ("The text value of the first Meida element:" + value);} public static void main (String [] args) {Textxml textxml = new Textxml (); textxml. xml ();}}

Running result

Entire document:
 
  
   
Image 1
      
  
   
Image 2
      
  
   
Image 3
  
 Response node Result property value: 1 First Media element:
 
  
Image 1
 Name attribute value of the first Media element: img_201301__141838.jpg text value of the first Meida element: Image 1

Postscript

1. there are many XML parsing methods, which may not have to be mastered in every way. it is enough to clarify one of them. The author cannot understand the performance differences, and cannot answer this question.

2. there are many DOM4J APIs. This article only introduces the most basic and commonly used APIs. if you are interested, you can study and use them on your own.

The above is the details of the sample code for DOM4J parsing in XML parsing. For more information, see other related articles in the first PHP community!

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.