用dom4j,解析xml 最好、最方便!

sunnylovecmc發表於2012-10-17

xml的解析工具有哪些,優缺點就不在這裡描述了。

目前推薦採用dom4j,所以這裡只是討論使用dom4j。

[java] view plaincopy
  1. //先加入dom4j.jar包  
  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.DocumentException;  
  8. import org.dom4j.DocumentHelper;  
  9. import org.dom4j.Element;  
  10.   
  11. /** 
  12.  * @description 解析xml字串 
  13.  * @author 無處不在 
  14.  * @Time 上午11:01:31 
  15.  */  
  16. public class Test {  
  17.   
  18.     public void readStringXml(String xml) {  
  19.         Document doc = null;  
  20.         try {  
  21.   
  22.             // 讀取並解析XML文件  
  23.             // SAXReader就是一個管道,用一個流的方式,把xml檔案讀出來  
  24.             //  
  25.             // SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文件  
  26.             // Document document = reader.read(new File("User.hbm.xml"));  
  27.             // 下面的是通過解析xml字串的  
  28.             doc = DocumentHelper.parseText(xml); // 將字串轉為XML  
  29.   
  30.             Element rootElt = doc.getRootElement(); // 獲取根節點  
  31.             System.out.println("根節點:" + rootElt.getName()); // 拿到根節點的名稱  
  32.   
  33.             Iterator iter = rootElt.elementIterator("head"); // 獲取根節點下的子節點head  
  34.   
  35.             // 遍歷head節點  
  36.             while (iter.hasNext()) {  
  37.   
  38.                 Element recordEle = (Element) iter.next();  
  39.                 String title = recordEle.elementTextTrim("title"); // 拿到head節點下的子節點title值  
  40.                 System.out.println("title:" + title);  
  41.   
  42.                 Iterator iters = recordEle.elementIterator("script"); // 獲取子節點head下的子節點script  
  43.   
  44.                 // 遍歷Header節點下的Response節點  
  45.                 while (iters.hasNext()) {  
  46.   
  47.                     Element itemEle = (Element) iters.next();  
  48.   
  49.                     String username = itemEle.elementTextTrim("username"); // 拿到head下的子節點script下的位元組點username的值  
  50.                     String password = itemEle.elementTextTrim("password");  
  51.   
  52.                     System.out.println("username:" + username);  
  53.                     System.out.println("password:" + password);  
  54.                 }  
  55.             }  
  56.             Iterator iterss = rootElt.elementIterator("body"); ///獲取根節點下的子節點body  
  57.             // 遍歷body節點  
  58.             while (iterss.hasNext()) {  
  59.   
  60.                 Element recordEless = (Element) iterss.next();  
  61.                 String result = recordEless.elementTextTrim("result"); // 拿到body節點下的子節點result值  
  62.                 System.out.println("result:" + result);  
  63.   
  64.                 Iterator itersElIterator = recordEless.elementIterator("form"); // 獲取子節點body下的子節點form  
  65.                 // 遍歷Header節點下的Response節點  
  66.                 while (itersElIterator.hasNext()) {  
  67.   
  68.                     Element itemEle = (Element) itersElIterator.next();  
  69.   
  70.                     String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子節點form下的位元組點banlce的值  
  71.                     String subID = itemEle.elementTextTrim("subID");  
  72.   
  73.                     System.out.println("banlce:" + banlce);  
  74.                     System.out.println("subID:" + subID);  
  75.                 }  
  76.             }  
  77.         } catch (DocumentException e) {  
  78.             e.printStackTrace();  
  79.   
  80.         } catch (Exception e) {  
  81.             e.printStackTrace();  
  82.   
  83.         }  
  84.     }  
  85.   
  86.     /** 
  87.      * @description 將xml字串轉換成map 
  88.      * @param xml 
  89.      * @return Map 
  90.      */  
  91.     public static Map readStringXmlOut(String xml) {  
  92.         Map map = new HashMap();  
  93.         Document doc = null;  
  94.         try {  
  95.             doc = DocumentHelper.parseText(xml); // 將字串轉為XML  
  96.             Element rootElt = doc.getRootElement(); // 獲取根節點  
  97.             System.out.println("根節點:" + rootElt.getName()); // 拿到根節點的名稱  
  98.   
  99.             Iterator iter = rootElt.elementIterator("head"); // 獲取根節點下的子節點head  
  100.             // 遍歷head節點  
  101.             while (iter.hasNext()) {  
  102.   
  103.                 Element recordEle = (Element) iter.next();  
  104.                 String title = recordEle.elementTextTrim("title"); // 拿到head節點下的子節點title值  
  105.                 System.out.println("title:" + title);  
  106.                 map.put("title", title);  
  107.   
  108.                 Iterator iters = recordEle.elementIterator("script"); // 獲取子節點head下的子節點script  
  109.   
  110.                 // 遍歷Header節點下的Response節點  
  111.                 while (iters.hasNext()) {  
  112.   
  113.                     Element itemEle = (Element) iters.next();  
  114.   
  115.                     String username = itemEle.elementTextTrim("username"); // 拿到head下的子節點script下的位元組點username的值  
  116.                     String password = itemEle.elementTextTrim("password");  
  117.   
  118.                     System.out.println("username:" + username);  
  119.                     System.out.println("password:" + password);  
  120.                     map.put("username", username);  
  121.                     map.put("password", password);  
  122.   
  123.                 }  
  124.             }  
  125.   
  126.             Iterator iterss = rootElt.elementIterator("body"); ///獲取根節點下的子節點body  
  127.             // 遍歷body節點  
  128.             while (iterss.hasNext()) {  
  129.                 Element recordEless = (Element) iterss.next();  
  130.                 String result = recordEless.elementTextTrim("result"); // 拿到body節點下的子節點result值  
  131.                 System.out.println("result:" + result);  
  132.   
  133.                 Iterator itersElIterator = recordEless.elementIterator("form"); // 獲取子節點body下的子節點form  
  134.                 // 遍歷Header節點下的Response節點  
  135.                 while (itersElIterator.hasNext()) {  
  136.   
  137.                     Element itemEle = (Element) itersElIterator.next();  
  138.   
  139.                     String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子節點form下的位元組點banlce的值  
  140.                     String subID = itemEle.elementTextTrim("subID");  
  141.   
  142.                     System.out.println("banlce:" + banlce);  
  143.                     System.out.println("subID:" + subID);  
  144.                     map.put("result", result);  
  145.                     map.put("banlce", banlce);  
  146.                     map.put("subID", subID);  
  147.                 }  
  148.             }  
  149.         } catch (DocumentException e) {  
  150.             e.printStackTrace();  
  151.         } catch (Exception e) {  
  152.             e.printStackTrace();  
  153.         }  
  154.         return map;  
  155.     }  
  156.   
  157.     public static void main(String[] args) {  
  158.   
  159.         // 下面是需要解析的xml字串例子  
  160.         String xmlString = "<html>" + "<head>" + "<title>dom4j解析一個例子</title>"  
  161.                 + "<script>" + "<username>yangrong</username>"  
  162.                 + "<password>123456</password>" + "</script>" + "</head>"  
  163.                 + "<body>" + "<result>0</result>" + "<form>"  
  164.                 + "<banlce>1000</banlce>" + "<subID>36242519880716</subID>"  
  165.                 + "</form>" + "</body>" + "</html>";  
  166.   
  167.         /* 
  168.          * Test2 test = new Test2(); test.readStringXml(xmlString); 
  169.          */  
  170.         Map map = readStringXmlOut(xmlString);  
  171.         Iterator iters = map.keySet().iterator();  
  172.         while (iters.hasNext()) {  
  173.             String key = iters.next().toString(); // 拿到鍵  
  174.             String val = map.get(key).toString(); // 拿到值  
  175.             System.out.println(key + "=" + val);  
  176.         }  
  177.     }  
  178.   
  179. }  



這裡遍歷了所有的子項。但是實際應用中,我們不需要遍歷所有的子節點。如果路徑到達三層,那麼解析起來就十分煩躁了。dom4j可以指定路徑,省去中間的遍歷。

[java] view plaincopy
  1. String xml ;//採用字串初始化Document。如果是普通檔案,可以採用上述程式碼中的方法。  
  2.   
  3. Document   document = DocumentHelper.parseText(xml);  
  4.   
  5. List<Element> targetElements = document.selectNodes("//head/sub/target");//直接得到target的Element 的列表,省去中間的查詢,判斷。  

dom4j還是很強大的,以後要多用用

相關文章