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

來源:互聯網
上載者:User

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檔案:

package com.qu.read;import java.io.File;import java.io.IOException;import javax.xml.parsers.*;import org.w3c.dom.Attr;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class ReadXML { public ReadXML() {  } public Document readXMLFile(String fileName) {  DocumentBuilderFactory factory =     DocumentBuilderFactory.newInstance();  Document doc = null;  try {   DocumentBuilder builder = factory.newDocumentBuilder();   File file = new File(fileName);   doc = builder.parse(file);  } catch (SAXException e) {      e.printStackTrace();  }catch (IOException e){   e.printStackTrace();  }catch (ParserConfigurationException e) {      e.printStackTrace();  }  return doc;    }  public void readXMLElements(NodeList nodeList) {  NamedNodeMap attributes =  null;    for (int i = 0; i < nodeList.getLength(); i++)  {   Node childNode =  nodeList.item(i);   String str = null;   if (childNode instanceof Element){    Element child =(Element) childNode;    if( child.getChildNodes().getLength() > 1){          str = "Element :" + child.getTagName() + ";";         }else{     str = "Element :" + child.getTagName();     str += " : " + child.getFirstChild().getNodeValue() + "  ";    }    attributes = child.getAttributes();    for (int j = 0; j < attributes.getLength(); j ++)    {     Node attr = attributes.item(j);     if (attr instanceof Attr){      String attrName = attr.getNodeName();      String attrValue = attr.getNodeValue();      str += "  Attribute " + attrName + " : " + attrValue + ";";     }         }    System.out.println(str);   }     } }  public static void main(String[] args) {  ReadXML readXML = new ReadXML();  Document doc = readXML.readXMLFile("E:/workspace/ReadXML/src/com/qu/xml/type.xml");  NodeList nodeList = doc.getElementsByTagName("*");  readXML.readXMLElements(nodeList); }}

 

 

  
   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.