Share a method for parsing an xml string using dom4j

Source: Internet
Author: User
Compared with the use of DOM, SAX, and JAXP mechanisms to parse xml, DOM4J is superior in performance, powerful in functionality, and extremely easy to use. as long as you understand the basic concepts of DOM, you can use the dom4j api documentation to parse xml. Dom4j is an open-source api. In actual projects, dom4j is often used as a tool for parsing xml. DOM4J

Compared with the use of DOM, SAX, and JAXP mechanisms to parse xml, DOM4J is superior in performance, powerful in functionality, and extremely easy to use. as long as you understand the basic concepts of DOM, you can use the dom4j api documentation to parse xml. Dom4j is an open-source api. In actual projects, dom4j is often used as a tool for parsing xml.

Let's take a look at the inheritance relationships established by the DOM tree corresponding to XML in dom4j.

In addition, the NodeType enumeration of dom4j implements the node type defined in the XML specification. In this way, you can use constants to determine the node type when traversing xml documents.

Common APIs

Class org. dom4j. io. SAXReader

  • Read provides multiple ways to read xml files and returns a Domcument object.

Interface org. dom4j. Document

  • Iterator uses this method to obtain the node

  • GetRootElement: get the root node

Interface org. dom4j. Node

  • GetName: Get the node name. for example, get the root node name as bookstore.

  • GetNodeType: Get the constant value of the node type. for example, get the bookstore type to 1 -- Element.

  • GetNodeTypeName: Get the node type name. for example, the obtained bookstore type name is Element.

Interface org. dom4j. Element

  • Attributes returns the attribute list of this element

  • AttributeValue obtains the attribute value based on the passed attribute name.

  • ElementIterator returns the iterator containing child elements

  • Elements returns a list containing child elements.

Interface org. dom4j. Attribute

  • GetName

  • GetValue

Interface org. dom4j. Text

  • GetText

Interface org. dom4j. CDATA

  • GetText: Get the CDATA Section value

Interface org. dom4j. Comment

  • GetText

Instance 1:

1 // add dom4j first. jar package 2 import java. util. hashMap; 3 import java. util. iterator; 4 import java. util. map; 5 6 import org. dom4j. document; 7 import org. dom4j. extends entexception; 8 import org. dom4j. export enthelper; 9 import org. dom4j. element; 10 11/** 12 * @ Title: TestDom4j. java 13 * @ Package 14 * @ Description: parsing xml strings 15 * @ author everywhere 16 * @ date 2012-11-20 05:14:05 17 * @ version V1.0 18 */19 public class TestDom4j {20 21 public void readStringXml (String xml) {22 Document doc = null; 23 try {24 25 // Read and parse the XML Document 26 // SAXReader is a pipe, using a stream, read the xml file 27 // 28 // SAXReader reader = new SAXReader (); // User. hbm. xml indicates the xml Document you want to parse 29 // document Document = reader. read (new File ("User. hbm. xml "); 30 // The following is the 31 doc = DocumentHelper. parseText (xml); // convert the string to XML 32 33 Element rootElt = doc. getRootElement (); // get the root node 34 System. out. println ("root node:" + rootElt. getName (); // get the root node name 35 36 Iterator iter = rootElt. elementIterator ("head"); // Obtain the child node head 37 under the root node 38 // traverse head node 39 while (iter. hasNext () {40 41 Element recordEle = (Element) iter. next (); 42 String title = recordEle. elementTextTrim ("title"); // obtain the title value of the subnode under the head node 43 System. out. println ("title:" + title); 44 45 Iterator iters = recordEle. elementIterator ("script"); // Obtain the subnode script 46 47 under the subnode head // traverse the Response node 48 while (iters. hasNext () {49 50 Element itemEle = (Element) iters. next (); 51 52 String username = itemEle. elementTextTrim ("username"); // get the username value of the byte point in the script of the subnode under the head 53 String password = itemEle. elementTextTrim ("password"); 54 55 System. out. println ("username:" + username); 56 System. out. println ("password:" + password); 57} 58} 59 Iterator iterss = rootElt. elementIterator ("body"); // Obtain the child node body under the root node 60 // traverse the body node 61 while (iterss. hasNext () {62 63 Element recordEless = (Element) iterss. next (); 64 String result = recordEless. elementTextTrim ("result"); // get the result value of the subnode under the body node 65 System. out. println ("result:" + result); 66 67 Iterator itersElIterator = recordEless. elementIterator ("form"); // Obtain the subnode form 68 under the subnode body // traverse the Response node 69 while (itersElIterator. hasNext () {70 71 Element itemEle = (Element) itersElIterator. next (); 72 73 String banlce = itemEle. elementTextTrim ("banlce"); // Get the banlce value of the byte point of the child node form under the body 74 String subID = itemEle. elementTextTrim ("subID"); 75 76 System. out. println ("banlce:" + banlce); 77 System. out. println ("subID:" + subID); 78} 79} 80} catch (incluentexception e) {81 e. printStackTrace (); 82 83} catch (Exception e) {84 e. printStackTrace (); 85 86} 87} 88 89/** 90 * @ description converts an xml String to map 91 * @ param xml 92 * @ return Map 93 */94 public static Map readStringXmlOut (String xml) {95 Map map = new HashMap (); 96 Document doc = null; 97 try {98 // convert the string to XML 99 doc = DocumentHelper. parseText (xml); 100 // get the root node 101 Element rootElt = doc. getRootElement (); 102 // get the root node name 103 System. out. println ("root node:" + rootElt. getName (); 104 105 // Obtain the child node head106 Iterator iter = rootElt under the root node. elementIterator ("head"); 107 // traverse head node 108 while (iter. hasNext () {109 110 Element recordEle = (Element) iter. next (); 111 // get the title value of the subnode under the head node 112 String title = recordEle. elementTextTrim ("title"); 113 System. out. println ("title:" + title); 114 map. put ("title", title); 115 // Obtain the subnode script116 Iterator iters = recordEle under the subnode head. elementIterator ("script"); 117 // traverses the Response node 118 while (iters. hasNext () {119 Element itemEle = (Element) iters. next (); 120 // get the username value of the byte point in the script of the subnode under the head: 121 String username = itemEle. elementTextTrim ("username"); 122 String password = itemEle. elementTextTrim ("password"); 123 124 System. out. println ("username:" + username); 125 System. out. println ("password:" + password); 126 map. put ("username", username); 127 map. put ("password", password); 128} 129} 130 131 // Obtain the subnode body132 Iterator iterss = rootElt under the root node. elementIterator ("body"); 133 // traverse the body node 134 while (iterss. hasNext () {135 Element recordEless = (Element) iterss. next (); 136 // get the result value of the subnode under the body node 137 String result = recordEless. elementTextTrim ("result"); 138 System. out. println ("result:" + result); 139 // Obtain the subnode form140 Iterator itersElIterator = recordEless under the subnode body. elementIterator ("form"); 141 // traverses the Response node 142 while (itersElIterator. hasNext () {143 Element itemEle = (Element) itersElIterator. next (); 144 // Get the banlce value of the byte point of the child node form under the body: 145 String banlce = itemEle. elementTextTrim ("banlce"); 146 String subID = itemEle. elementTextTrim ("subID"); 147 148 System. out. println ("banlce:" + banlce); 149 System. out. println ("subID:" + subID); 150 map. put ("result", result); 151 map. put ("banlce", banlce); 152 map. put ("subID", subID); 153} 154} 155} catch (incluentexception e) {156 e. printStackTrace (); 157} catch (Exception e) {158 e. printStackTrace (); 159} 160 return map; 161} 162 163 public static void main (String [] args) {164 165 // The following is an example of an xml String to be parsed: 166 String xmlString =""+""+"Dom4j parsing example"167 +" script "+"
 
  
Yangrong
 "168 +"
 
  
123456
 "+" Script "+""169 +""+"
 
  
0
 "+" "+""+""; 172 173/* 174 * Test2 test = new Test2 (); test. readStringXml (xmlString); 175 */176 Map map = readStringXmlOut (xmlString); 177 Iterator iters = map. keySet (). iterator (); 178 while (iters. hasNext () {179 String key = iters. next (). toString (); // Obtain the key 180 String val = map. get (key ). toString (); // get the value 181 System. out. println (key + "=" + val); 182} 183} 184 185} instance 2:
1/** 2 * parse the XML file containing DB connection information. 3 * the format must comply with the following specifications: 4*1. A maximum of three levels, with custom node names; 5*2. secondary nodes support node attributes, which are considered as subnodes; 6*3. CDATA must be included in the node and cannot appear separately. 7*8 * Example 1 -- three-level display: 9 *
 
  
10 *
  
   
11 *
   
    
DBTest
   12 *
   13 *
   
    
14 *jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=UTF815 *
   16 *
   
    
Org. gjt. mm. mysql. Driver
   17 *
   
    
Test
   18 *
   
    
Test2012
   19 *
   
    
10
   20 *
   
    
10
   21 *
   
    
2
   22 *
   
    
10
   23 *
   
    
SELECT 1 + 1
   24 *
  25 *
 26*27 * Example 2 -- node attribute: 28 *
 
  
29 *
  
   
30 *
   Everyday Italian31 * Giada De Laurentiis32 *
   
    
2005
   33 *
   
    
30.00
   34 *
  35*36 *
  37 *
 38*39 * @ param configFile40 * @ return41 * @ throws Exception42 */43 public static List
 
  
> ParseDBXML (String configFile) throws Exception {44 List
  
   
> DbConnections = new ArrayList
   
    
> (); 45 InputStream is = Parser. class. getResourceAsStream (configFile); 46 SAXReader saxReader = new SAXReader (); 47 Document document = saxReader. read (is); 48 Element connections = document. getRootElement (); 49 50 Iterator
    
     
RootIter = connections. elementIterator (); 51 while (rootIter. hasNext () {52 Element connection = rootIter. next (); 53 Iterator
     
      
ChildIter = connection. elementIterator (); 54 Map
      
        ConnectionInfo = new HashMap
       
         (); 55 List attributes = connection. attributes (); 56 for (int I = 0; I <attributes. size (); ++ I) {// add node attribute 57 connectionInfo. put (attributes. get (I ). getName (), attributes. get (I ). getValue (); 58} 59 while (childIter. hasNext () {// add the subnode 60 Element attr = childIter. next (); 61 connectionInfo. put (attr. getName (). trim (), attr. getText (). trim (); 62} 63 dbConnections. add (connectionInfo); 64} 65 66 return dbConnections; 67}
       
      
     
    
   
  
 

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.