1. 程式人生 > >DOM解析核心類庫預覽

DOM解析核心類庫預覽

Java中的DOM解析

  • xml文件的主要作用就是用於資料的儲存,java中定義有一些對xml檔案內容讀取的類庫,DOM解析技術就是其中一種,其他還有"SAX"解析,JDOM解析,DOM4J解析,

  • 其中DOM解析是w3c定義的一套標準介面規範,主要的特點就是跨平臺(其他語言也有這種技術,例如JavaScript),DOM解析時需要將整個xml檔案載入到記憶體中,所以在讀取比較小的xml檔案的時候,查詢資料速度較快.這也是w3c(全球資訊網聯盟)所推薦的一種方式.

  • 缺點就是:如果xml檔案過大,那麼DOM解析讀取資料的速度可能變慢.

  • 示例:如果有以下的一段xml檔案,使用DOM解析該如何去除xml中的資料內容

<?xml version="1.0" encoding="utf-8"?>
<shop>
	<book>
		<name>新的世界,新的你</name>
		<year>3</year>
		<price >56.6</price>
	</book>
	<book>
		<name>java入門到跑路</name>
		<year>111</year>
		<price >100</price>
	</
book
>
</shop>

DocumentBuilderFactory類

  • 要讀取一個xml檔案,首先需要一個讀取xml檔案的解析器,解析器的作用就是讀取xml檔案內容,而生成一個樹結構資料.
  • 在java中要得到一個DOM解析器需要通過java中的DocumentBuilderFactory這個類來取得解析器工廠物件(DocumentFactory介面),該類是一個抽象類,所以需要使用該類中的newInstance()方法獲取到該類的例項化物件.
  • 而後使用newDocumentBuilder()這個方法,取得DocumentBuilder介面例項化物件
DocumentBuilderFactory解析器工廠類主要方法
public static DocumentBuilderFactory newInstance() 得到DocumentBuilderFactory類物件
public abstract DocumentBuilder newDocumentBuilder()throws ParserConfigurationException 得到XML文件建立類物件(DOM解析器)
  • 1. 建立一個TestXmlDoc.java程式類
public class TestXmlDom {
    public static void main(String[] args)throws Exception{
        //取得直譯器工廠類物件
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

    }
}

DcoumnetBuilder:文件建立類

  • 得到DocumentBuilder類物件之後,就可以通過這個物件完成對一個xml檔案的解析,並將xml檔案解析為一個物件返回.
  • 在DOM中一整個XML檔案就是一個檔案節點,所以java中使用Document類描述一個xml檔案
DocumentBuilder類主要方法
public abstract Document newDocument() 建立一個XML文件節點
public Document parse(File f)throws SAXException, IOException 將一個檔案解析為一個Document物件
public Document parse(String uri) throws SAXException, IOException 給定一個檔案路徑,將這個檔案轉換為一個Document物件
public Document parse(InputStream is)throws SAXException, IOException 根據一個位元組流,解析為一個Document物件
  • 2. xml檔案為本地e盤中的檔案,所以就是用java中的File類來描述這個檔案
    • xml檔案所在的路徑"E:\testWeb\info.xml"
    • 在TestXmlDom.java程式類中解析xml檔案
public class TestXmlDom {
    public static void main(String[] args)throws Exception{
        //取得直譯器工廠類物件
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        //描述xml檔案
        File xmlFile = new File("E:"+File.separator+"testWeb"+File.separator+"info.xml");
        //解析xml檔案
        Document xmlDoc = documentBuilder.parse(xmlFile);

    }
}

文件處理操作介面Document

  • Document介面,他繼承自org.w3c.dom.Node介面,Document描述一整個xml檔案,在DOC中一個xml檔案為一個文件節點,其他所有節點都在文件節點之下,包括根節點.
Document操作介面的主要方法
Attr createAttribute(String name) throws DOMException 建立給定名稱的屬性物件(Attr介面表示一個節點的屬性)
Element createElement(String tagName)throws DOMException 根據一個名稱,建立一個元素
Text createTextNode(String data) 建立一個文字節點
NodeList getElementsByTagName(String tagname) 通過指定的節點名稱,取得一個NodeList集合
  • 3. 取得所有book節點
public class TestXmlDom {
    public static void main(String[] args)throws Exception{
        //取得直譯器工廠類物件
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        //描述xml檔案
        File xmlFile = new File("E:"+File.separator+"testWeb"+File.separator+"info.xml");
        //解析xml檔案
        Document xmlDoc = documentBuilder.parse(xmlFile);
        //取得根節點下的所有子節點
        NodeList allNode = xmlDoc.getElementsByTagName("book");
        	
    }
}

org.w3c.dom.Node節點處理介面

  • DOM操作中每一個節點都是用Node介面描述,DOM中許多操作介面都繼承自Node介面,例如Document,Attr,Element
  • 在Node介面中可以獲取到一個節點的名稱,內容.
Node介面的主要操作方法
Node appendChild(Node newChild) throws DOMException 在當前節點中追加一個子節點
Node cloneNode(boolean deep) 克隆一個子節點
NodeList getChildNodes() 得到所有子元素, 返回一個包含該節點的所有子節點NodeList集合
String getNodeName() 取得節點名稱
getLastChild() 得到最後一個子元素
short getNodeType() 取得節點型別,節點的型別使用Node介面中定義的短整型常量表示
String getNodeValue() throws DOMException 取得節點內容
Node getParentNode() 取得該節點的父節點
String getTextContent() throws DOMException 取得節點的文字內容
boolean hasAttributes() 判斷該節點是否有屬性
boolean hasChildNodes() 判斷該節點下是否有子元素
Node removeChild(Node oldChild)throws DOMException 刪除當前節點下的子節點,並返回刪除的子節點
Node replaceChild(Node newChild, Node oldChild)throws DOMException() 替換子節點,並返回被取代的節點
void setTextContent(String textContent) throws DOMException 設定文字內容
  • 4. 此時的程式已經得到了兩個book節點,通過迴圈,再取出book節點下的所有子元素
    • 因為Element介面也繼承自Node介面,因此可以進行向下轉型
    • 而Element介面中定義有根據元素名稱取得指定元素的方法,所以需要向下轉型為Element
 public static void main(String[] args)throws Exception{
        //取得直譯器工廠類物件
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        //描述xml檔案
        File xmlFile = new File("E:"+File.separator+"testWeb"+File.separator+"info.xml");
        //解析xml檔案
        Document xmlDoc = documentBuilder.parse(xmlFile);
        //取得根節點下的所有子節點(book)
        NodeList allNode = xmlDoc.getElementsByTagName("shop");
        //迴圈取出每一個子節點
        for (int i = 0; i < allNode.getLength(); i++) {
        	//取出book節點下的所子元素
             Element item = (Element)allNode.item(i);
           
        }
    }

Element:元素描述介面

  • Element介面用於描述xml檔案中的一個元素,元素代表xml中的一個標籤,而Node介面描述xml檔案中任何一個內容(文件,註釋,標籤,文字,屬性等),所以Element屬於Node,Element介面也直接繼承自Node介面,可以直接使用Node介面中的方法來獲取Element介面物件.
Element中的主要方法
String getAttribute(String name) 得到指定的屬性內容
void setAttribute(String name,String value) throws DOMException 設定指定名稱的屬性內容,如果該屬性不存在,則建立一個新的屬性
NodeList getElementsByTagName(String name) 取得所有指定元素標籤名的節點集合
String getTagName() 取得元素標籤名稱
void removeAttribute(String name) throws DOMException 刪除指定名稱的屬性,如果該屬性不存在則方法無效
  • 取出xml檔案中的元素內容
public static void main(String[] args)throws Exception{
        //取得直譯器工廠類物件
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

        //描述xml檔案
        File xmlFile = new File("E:"+File.separator+"testWeb"+File.separator+"info.xml");
        //解析xml檔案
        Document xmlDoc = documentBuilder.parse(xmlFile);
        //取得根節點下的所有子節點(book)
        NodeList allNode = xmlDoc.getElementsByTagName("book");
        //迴圈取出每一個子節點
        for (int i = 0; i < allNode.getLength(); i++) {
            Element item = (Element)allNode.item(i);
            System.out.println("書名 : "+ item.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
            System.out.println("出版時間 : "+ item.getElementsByTagName("year").item(0).getFirstChild().getNodeValue());
            System.out.println("價格 : "+ item.getElementsByTagName("price").item(0).getFirstChild().getNodeValue());

        }
    }
  • 控制檯輸出結果

在這裡插入圖片描述

文字描述,org.w3c.dom.Text

  • Text介面描述xml文件中元素的字串部分,例如"2018年12月31日19:14:03"內容就屬於"date"元素的字串部分.
<date>2018年12月31日19:13:40</date>

屬性描述:org.w3c.dom.Attr

  • Attr介面描述xml文件中的元素的屬性,Attr也繼承自Node介面,Attr與其他物件(Element,Text,等有關聯但但他們是截然不同的)
String getName() 取得屬性名稱
String getValue() 取得屬內容
void setValue(String value) throws DOMException 設定 屬性內容

核心類的關係圖

在這裡插入圖片描述