Java DOM解析XML的幾個例子

Sample1:

1:新建XML文檔 books.xml,放到項目的根目錄下。

[html] view plain copy
  1. <?xml version="1.0" encoding="GB2312"?>    
  2. <books  count="3"    
  3.     xmlns="http://test.org/books">    
  4.     <!--books's comment-->    
  5.     <book id="1">    
  6.         <name>Thinking in JAVA</name>    
  7.     </book>    
  8.     <book id="2">    
  9.         <name>Core JAVA2</name>    
  10.     </book>    
  11.     <book id="3">    
  12.         <name>C++ primer</name>    
  13.     </book>    
  14. </books>    


2:java解析代碼如下:

[html] view plain copy
  1. package com.dom.test;  
  2.   
  3. import java.io.File;     
  4. import java.io.IOException;     
  5.     
  6. import javax.xml.parsers.DocumentBuilder;     
  7. import javax.xml.parsers.DocumentBuilderFactory;     
  8. import javax.xml.parsers.ParserConfigurationException;     
  9.     
  10. import org.w3c.dom.Document;     
  11. import org.w3c.dom.Element;     
  12. import org.w3c.dom.NamedNodeMap;     
  13. import org.w3c.dom.Node;     
  14. import org.w3c.dom.NodeList;     
  15. import org.xml.sax.SAXException;     
  16.     
  17. public class Test {     
  18.     public static void main(String[] args) throws ParserConfigurationException,     
  19.             SAXException, IOException {     
  20.         DocumentBuilderFactory builderFactory = DocumentBuilderFactory     
  21.                 .newInstance();     
  22.         DocumentBuilder builder = builderFactory.newDocumentBuilder();     
  23.         /*    
  24.          * builder.parse()方法將給定文件的內容解析爲一個 XML 文檔, 並且返回一個新的 DOM Document對象。    
  25.          */    
  26.         Document document = builder.parse(new File("books.xml"));     
  27.         //打印document節點     
  28.         printNode(document,0);     
  29.              
  30.         //獲取文檔的根元素,賦值給rootElement變量     
  31.         Element rootElement = document.getDocumentElement();     
  32.         //獲取根元素的count屬性     
  33.         int countOfBooks = Integer.parseInt(rootElement.getAttribute("count"));     
  34.         String str = rootElement.getAttribute("xmlns");  
  35.         System.out.println(str);  
  36.         System.out.println("There are "+countOfBooks+" books , they are ");     
  37.           
  38.         //獲取rootElement的所有子節點(不包括屬性節點),返回一個NodeList對象     
  39.         NodeList childNodes = rootElement.getChildNodes();     
  40.         for(int i = 0;i < childNodes.getLength();i++){     
  41.             //獲取childNodes的第i個節點     
  42.             Node childNode = childNodes.item(i);     
  43.             //判斷childNode是不是一個元素節點,並且它的 nodeName 值爲book     
  44.             if(childNode.getNodeType() == Node.ELEMENT_NODE      
  45.                     && childNode.getNodeName().equals("book")){     
  46.                 //若是,則獲取childNode的所有子節點(不包括屬性節點),返回一個NodeList對象     
  47.                 NodeList childNodes_2 = childNode.getChildNodes();     
  48.                 for(int j = 0;j < childNodes_2.getLength();j++){     
  49.                     //獲取childNodes_2的第j個節點     
  50.                     Node childNode_2 = childNodes_2.item(j);     
  51.                     //判斷childNode_2是不是一個元素節點,並且它的 nodeName 值爲name     
  52.                     if(childNode_2.getNodeType() == Node.ELEMENT_NODE      
  53.                             && childNode_2.getNodeName().equals("name")){     
  54.                         //若是,則獲取childNode_2的所有子節點(不包括屬性節點),返回一個NodeList對象     
  55.                         NodeList childNodes_3 = childNode_2.getChildNodes();     
  56.                         for(int k = 0;k < childNodes_3.getLength();k++){     
  57.                             //獲取childNodes_3的第k個節點     
  58.                             Node childNode_3 = childNodes_3.item(k);     
  59.                             //判斷childNodes_3是不是一個文本節點     
  60.                             if(childNode_3.getNodeType() == Node.TEXT_NODE){     
  61.                                 //若是,則打印輸出這個文本節點的nodeValue     
  62.                                 System.out.println("  <<"+childNode_3.getNodeValue()+">>");     
  63.                             }     
  64.                         }     
  65.                     }     
  66.                 }     
  67.             }     
  68.         }     
  69.     }     
  70.          
  71.     /*    
  72.      * 打印 DOM 節點    
  73.      * 輸出格式爲:    
  74.      *     nodeType(nodeName,nodeValue)    
  75.      *         "ATTRIBUTE"(attributeName=attributeValue)    
  76.      *         ...    
  77.      *         childNodeType[childNodeName,childNodeValue]    
  78.      *         ...    
  79.      */    
  80.     public static void printNode(Node node,int count) {     
  81.         if (node != null) {     
  82.             String tmp = "";     
  83.             for(int i = 0 ; i < count ; i++) tmp += "  ";     
  84.             //獲取node節點的節點類型,賦值給nodeType變量     
  85.             int nodeType = node.getNodeType();     
  86.             switch (nodeType) {     
  87.                 case Node.ATTRIBUTE_NODE: tmp += "ATTRIBUTE";break;     
  88.                 case Node.CDATA_SECTION_NODE: tmp += "CDATA_SECTION";break;     
  89.                 case Node.COMMENT_NODE:tmp += "COMMENT";break;     
  90.                 case Node.DOCUMENT_FRAGMENT_NODE:tmp += "DOCUMENT_FRAGMENT";break;     
  91.                 case Node.DOCUMENT_NODE:tmp += "DOCUMENT";break;     
  92.                 case Node.DOCUMENT_TYPE_NODE:tmp += "DOCUMENT_TYPE";break;     
  93.                 case Node.ELEMENT_NODE:tmp += "ELEMENT";break;     
  94.                 case Node.ENTITY_NODE:tmp += "ENTITY";break;     
  95.                 case Node.ENTITY_REFERENCE_NODE:tmp += "ENTITY_REFERENCE";break;     
  96.                 case Node.NOTATION_NODE:tmp += "NOTATION";break;     
  97.                 case Node.PROCESSING_INSTRUCTION_NODE:tmp += "PROCESSING_INSTRUCTION";break;     
  98.                 case Node.TEXT_NODE:tmp += "TEXT";break;     
  99.                 default:return;//invalid node type.     
  100.             }     
  101.                  
  102.             System.out.println(tmp+" ("+node.getNodeName()+","+node.getNodeValue()+")");     
  103.             /*    
  104.              * node.getAttributes()方法返回    
  105.              * 包含node節點的屬性的 NamedNodeMap(如果它是 Element)    
  106.              */    
  107.             NamedNodeMap attrs = node.getAttributes();     
  108.             if(attrs != null)     
  109.                 for(int i = 0 ; i < attrs.getLength() ; i++){     
  110.                     printNode(attrs.item(i),count+1);     
  111.                 }     
  112.             /*    
  113.              * node.getChildNodes()方法返回    
  114.              * 包含node節點的所有子節點的 NodeList。    
  115.              */    
  116.             NodeList childNodes = node.getChildNodes();     
  117.             for(int i = 0 ; i < childNodes.getLength() ; i++){     
  118.                 printNode(childNodes.item(i),count+1);     
  119.             }     
  120.         }     
  121.     }     
  122. }    


3:運行上面的Test.java即可測試。


Sample2:

1:新建XML文檔 persons.xml,放到項目的根目錄下。

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <persons>  
  3.     
  4.   <person><name>kalision</name><sex></sex></person>  
  5.     
  6.   <person>  
  7.     <name>kity</name>  
  8.     <sex></sex>  
  9.   </person>  
  10.     
  11.   <person>  
  12.     <name>qizai</name>  
  13.     <sex></sex>  
  14.   </person>  
  15.     
  16. </persons>  


2:java解析代碼如下:

[html] view plain copy
  1. package net.vicp.jiasoft;  
  2.   
  3. import javax.xml.parsers.*;  
  4. import java.io.IOException;  
  5. import org.xml.sax.SAXException;  
  6. import org.w3c.dom.Document;  
  7. import org.w3c.dom.NodeList;  
  8. import org.w3c.dom.Node;  
  9.   
  10. public class DomXml {  
  11.      public void parsersXml() {  
  12.          //實例化一個文檔構建器工廠  
  13.          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
  14.          try {  
  15.              //通過文檔構建器工廠獲取一個文檔構建器  
  16.              DocumentBuilder db = dbf.newDocumentBuilder();  
  17.              //通過文檔通過文檔構建器構建一個文檔實例  
  18.              Document doc = db.parse("persons.xml");  
  19.              //獲取所有名字爲 “person” 的節點  
  20.              NodeList nl1 = doc.getElementsByTagName("person");  
  21.              int size1 = nl1.getLength();  
  22.              System.out.println("該名稱的節點長度爲:" + size1);  
  23.              for (int i = 0; i < size1; i++) {  
  24.                  Node n = nl1.item(i);  
  25.                  //獲取 n 節點下所有的子節點。此處值得注意,在DOM解析時會將所有回車都視爲 n 節點的子節點。  
  26.                  NodeList nl2 = n.getChildNodes();  
  27.                  //因爲上面的原因,在此例中第一個 n 節點有 2 個子節點,而第二個 n 節點則有 5 個子節點(因爲多了3個回車)。  
  28.                  int size2 = nl2.getLength();  
  29.                  System.out.println("N節點的第一個子節點的長度爲:" + size2);  
  30.                  for (int j = 0; j < size2; j++) {  
  31.                      Node n2 = nl2.item(j);  
  32.                      //還是因爲上面的原因,故此要處判斷當 n2 節點有子節點的時才輸出。  
  33.                      if (n2.hasChildNodes()) {  
  34.                          System.out.println(n2.getNodeName() + " = " +  
  35.                                             n2.getFirstChild().getNodeValue());  
  36.                      }  
  37.                  }  
  38.              }  
  39.          } catch (ParserConfigurationException ex) {  
  40.              ex.printStackTrace();  
  41.          } catch (IOException ex) {  
  42.              ex.printStackTrace();  
  43.          } catch (SAXException ex) {  
  44.              ex.printStackTrace();  
  45.          }  
  46.      }  
  47.    
  48.      public static void main(String[] args) {  
  49.          DomXml domxml = new DomXml();  
  50.          domxml.parsersXml();  
  51.      }  
  52.  }  


3:運行上面的DomXml.java即可測試。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章