Use Dom4j to parse XML files containing DB connection information and obtain node attributes.
XML file containing DB connection information
1 <! -- Example 1 -- three-level display --> 2 <db-connections> 3 <connection> 4 <name> DBTest </name> 5 <jndi> </jndi> 6 <url> 7 <! [CDATA [jdbc: mysql: // localhost: 3306/db_test? UseUnicode = true & characterEncoding = UTF8]> 8 </url> 9 <driver> org. gjt. mm. mysql. driver </driver> 10 <user> test </user> 11 <password> test2012 </password> 12 <max-active> 10 </max-active> 13 <max- idle> 10 </max-idle> 14 <min-idle> 2 </min-idle> 15 <max-wait> 10 </max-wait> 16 <validation-query> SELECT 1 + 1 </validation-query> 17 </connection> 18 </db-connections>Db-connections.xml
Node attribute XML file
1 <! -- Example 2 -- node attributes --> 2 <bookstore> 3 <book category = "cooking"> 4 <title lang = "en"> Everyday Italian </title> 5 <author> GB Ada De Laurentiis </author> 6 <year> 2005 </year> 7 <price> 30.00 </price> 8 </book> 9 <book category = "children" title = "Harry Potter" author = "j k. rowling "year =" 2005 "price =" $29.9 "/> 10 </bookstore>Bookstore. xml
Parsing Code:
1 package xml; 2 3 import java. io. file; 4 import java. io. fileInputStream; 5 import java. util. arrayList; 6 import java. util. hashMap; 7 import java. util. iterator; 8 import java. util. list; 9 import java. util. map; 10 11 import org. dom4j. attribute; 12 import org. dom4j. document; 13 import org. dom4j. element; 14 import org. dom4j. io. SAXReader; 15 16 public class TestDom4j2 {17 18/*** 19 * Parse XML file containing DB connection information in 20 * Format Must comply with the following specifications: 21*1. A maximum of three levels, with custom node names; 22*2. secondary nodes support node attributes, which are considered as subnodes; 23*3. CDATA must be included in the node and cannot appear separately. 24 */25 public static List <Map <String, String> parseDBXML (String configFile) throws Exception {26 List <Map <String, string> dbConnections = new ArrayList <Map <String, String> (); 27 // query files from the JAVA project path, the file must be in the src Source package path to use this method 28 // InputStream is = TestDom4j2. class. getResourceAsStream (configFile); 29 30 // get the content of the xml File from the drive letter 31 FileInputStream is = new FileInputStream (new File (configFile); 32 SAXReader saxReader = new SAXReader (); 33 Document document = saxReader. read (is); 34 // get the root node db-connections or bookstore35 Element connections = document. getRootElement (); 36 37 Iterator <Element> rootIter = connections. elementIterator (); 38 while (rootIter. hasNext () {39 Element connection = rootIter. next (); 40 Iterator <Element> childIter = connection. elementIterator (); 41 42 Map <String, String> connectionInfo = new HashMap <String, String> (); 43 // obtain all attributes of the connection or book node 44 List <Attribute> attributes = connection. attributes (); 45 // traverse node attributes 46 for (int I = 0; I <attributes. size (); ++ I) {47 // Add the node property value 48 connectionInfo. put (attributes. get (I ). getName (), attributes. get (I ). getValue (); 49} 50 // traverse the connection or book subnode 51 while (childIter. hasNext () {52 // Add sub-node 53 Element attr = childIter. next (); 54 connectionInfo. put (attr. getName (). trim (), attr. getText (). trim (); 55} 56 dbConnections. add (connectionInfo); 57} 58 return dbConnections; 59} 60 61 public static void main (String [] args) {62 try {63 List <Map <String, string> dbList = parseDBXML ("E: // xml // db-connections.xml"); 64 System. out. println ("URL =" + dbList. get (0 ). get ("url"); 65 66 System. out. println (); 67 68 List <Map <String, String> list = parseDBXML ("E: // xml // bookstore. xml "); 69 for (int I = 0; I <list. size (); I ++) {70 System. out. println ("title =" + list. get (I ). get ("title"); 71 System. out. println ("author =" + list. get (I ). get ("author"); 72 System. out. println ("year =" + list. get (I ). get ("year"); 73 System. out. println ("price =" + list. get (I ). get ("price"); 74} 75} catch (Exception e) {76 e. printStackTrace (); 77} 78} 79}
Running result:
URL=jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=UTF8title=Everyday Italianauthor=Giada De Laurentiisyear=2005price=30.00title=Harry Potterauthor=J K. Rowlingyear=2005price=$29.9
How does dom4j Parse xml files in java to obtain node attributes?
In dom4j, you can use the Element. attributes method to obtain the node attributes, and use elements to obtain the corresponding subnodes.
For example:
Element root = doc. getRootElement ();
List attrList = root. attributes ();
For (int I = 0; I <attrList. size (); I ++ ){
// Obtain attributes
Attribute item = (Attribute) attrList. get (I );
System. out. println (item. getName () + "=" + item. getValue ());
}
List childList = root. elements ();
For (int I = 0; I <childList. size (); I ++ ){
// Subnode operations
Element it = (Element) childList. get (I );
// Perform other operations on the subnode...
}
How to Use dom4j to parse multi-node xml files? Examples
According to your xml format. Save the preceding xml as bb. xml
SAXReader sax = new SAXReader ();
Document document = sax. read ("bb. xml ");
Element root = document. getRootElement ();
For (Iterator iter = root. elementIterator (); iter. hasNext ();){
Element vals = (Element) iter. next ();
System. out. println ("name =" + vals. getName ()
+ "\ T attribut ID =" + vals. attributeValue ("id "));
For (Iterator iterVal = vals. elementIterator (); iterVal
. HasNext ();){
Element valNode = (Element) iterVal. next ();
System. out. print ("\ t childName =" + valNode. getName ()
+ "\ T childValue =" + valNode. getText ());
System. out. println ();
}
}
If you change the xml format, save the file B. xml:
<RESULT>
<VALUE id = "13" type = "1">
<NO> 2 </NO>
<ADDR> test </ADDR>
</VALUE>
<VALUE id = "13" type = "2">
<NO> 2 </NO>
<ADDR> test </ADDR>
</VALUE>
</RESULT>
Resolution:
Document = sax. read ("B. xml ");
Root = document. getRootElement ();
List ls = root. selectNodes ("/RESULT/VALUE ");
For (int I = 0; I <ls. size (); I ++ ){
Element val = (Element) ls. get (I );
Element no = val. element ("NO ");
Element addr = val. element ("ADDR ");
System. out. println ("id =" + val. attributeValue ("id") + "\ t type ="
+ Val. attributeValue (... the remaining full text>