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即可测试。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章