使用Java和JAXP對XML文檔進行訪問


XML系列:使用Java和JAXP對XML文檔進行訪問和操作

一,Java訪問XML文檔
 導入java.xml.parsers包和org.w3c.dom包
 
 org.w3c.dom包包含了DOM解析器接口類型的定義。
 
 1,獲取java.xml.parsers.DocumentBuilder類:爲加載和分析XML文檔提供接口,也就是XML分析程序接口。
  可以把JAXP配置成不同XML分析程序,java.xml.parsers.DocumentBuilderFactory用於獲取一個分析程序的示例。
  使用DocumentBuilderFactory爲當前的XML分析程序實例化一個DocumentBuilder對象。
   DocumentBuilderFactory factory =  DocumentBuilderFactory.newInsrance();
   DocumentBuilder builder = factory.newDocumentBuilder();
 2,加載和分析XML文檔,如果加載成功則返回一個org.w3c.dom.Document對象,
   該對象是XML文檔樹形結構在內存中的表現。如果失敗則拋出SAXException。
   Document對象由實現Node接口及其多個子接口的類的對象構成。
   
   File file = new File("type.xml");
   Document doc = builder.parse(file);
   
 3,Document對象的getDocumentElement方法獲取根節點對象,getTagName方法返回節點的標籤名
   
   Element root = doc.getDocumentElement();
   String rootName = doc.getTagName();

 
 4,Element對象的getChildNodes方法獲取元素的子元素,返回結果爲NodeList集合。
   getElementByTagName或getElementById,通過指定元素名或ID來獲取該元素的子元素集合,返回結果爲NodeList集合。
   NodeList children = root.getChildNodes();
   或
   NodeList children = root.getElementByTagName("type");
   使用item方法遍歷集合,getLength提供集合元素的總數。
   
   
遍歷NodeList集合:
    Element e = null;
    for(int i = 0; i < children.getLength(); i ++)
    {
     Node child = children.item(i);
     e = (Element) child;
     System.out.println(e.getTagName() + " : " + e.getFirstChild().getNodeValue());
    }
   
   遍歷NodeList集合:只得到子元素,使用instanceof運算符進行類型檢查。

    for(int i = 0; i < children.getLength(); i ++)
    {
     Node child = children.item(i);
     if (child instanceof Element)
     {
      Element e = (Element) child;
      System.out.println(e.getTagName() + " : " + e.getNodeValue());    
     }
    }  
   遍歷NodeList集合:
    獲取當前節點的第一個getFirstChild方法和下一個子節點getNextChild方法,沒有節點的時候返回null。
     for (Node childNode = children.getFirstChild(); childNode != null;
        childeNode = childNode.getNextChild) {
      if(childNode instanceof Element){
       .....;
      }  
     }
 5,Element元素的getAttributes方法獲取元素的的屬性集合,返回結果爲NamedNodeMap對象。
   可以像使用遍歷NodeList集合一樣遍歷NamedNodeMap
   NamedNodeMap attributes = root.getAttributes();
   
   遍歷NamedNodeMap集合:
   for (int i = 0; i < attributes.getLength(); i++)
   {
    Node attribute = attributes.item(i);
    String attributeName = attribute.getNodeName();
    String attributeValue = attribute.getNodeValue();
   }
   
例子: 
XML文檔(type.xml):

 <?xml version="1.0" encoding="UTF-8"?>
<type xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="type1.xsd">
 <student state="true">
  <info>
   <name>張三</name>
   <sex>男</sex>
  </info>
  <grede>
   <chinese>1</chinese>
   <math>119</math>
  </grede>
 </student>
 <teacher state="true">
  <name>李四</name>
  <sex>女</sex>
  <subject>數學</subject>
 </teacher>
</type>    
java文件:


 

 

  
   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章