XML DOM - 屬性和方法

屬性和方法向 XML DOM 定義了編程接口。

實例

下面的例子使用 XML 文件 books.xml

函數 loadXMLDoc(),位于外部 JavaScript 中,用于加載 XML 文件。

函數 loadXMLString(),位于外部 JavaScript 中,用于加載 XML 字符串。

加載并解析 XML 文件
加載并解析 XML 字符串

編程接口

DOM 把 XML 模擬為一系列節點接口。可通過 JavaScript 或其他編程語言來訪問節點。在本教程中,我們使用 JavaScript。

對 DOM 的編程接口是通過一套標準的屬性和方法來定義的。

屬性經常按照“某事物是什么”的方式來使用(例如節點名是 "book")。

方法經常按照“對某事物做什么”的方式來使用(例如刪除 "book" 節點)。

XML DOM 屬性

一些典型的 DOM 屬性:

  • x.nodeName - x 的名稱
  • x.nodeValue - x 的值
  • x.parentNode - x 的父節點
  • x.childNodes - x 的子節點
  • x.attributes - x 的屬性節點

注釋:在上面的列表中,x 是一個節點對象。

XML DOM 方法

  • x.getElementsByTagName(name) - 獲取帶有指定標簽名稱的所有元素
  • x.appendChild(node) - 向 x 插入子節點
  • x.removeChild(node) - 從 x 刪除子節點

注釋:在上面的列表中,x 是一個節點對象。

實例

從 books.xml 中的 <title> 元素獲取文本的 JavaScript 代碼:

txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue

在此語句執行后,txt 保存的值是 "Harry Potter"。

解釋:

  • xmlDoc - 由解析器創建的 XML DOM
  • getElementsByTagName("title")[0] - 第一個 <title> 元素
  • childNodes[0] - <title> 元素的第一個子節點 (文本節點)
  • nodeValue - 節點的值 (文本自身)

在上面的例子中,getElementsByTagName 是方法,而 childNodes 和 nodeValue 是屬性。

解析 XML 文件 - 跨瀏覽器實例

下面的代碼片段使用 loadXMLDoc 函數把 books.xml 載入 XML 解析器中,并顯示第一個 book 的數據:

xmlDoc=loadXMLDoc("books.xml");
document.write(xmlDoc.getElementsByTagName("title")
[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("author")
[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("year")
[0].childNodes[0].nodeValue);

輸出:

Harry Potter
J K. Rowling
2005

TIY

在上面的例子中,我們為每個文本節點使用 childNodes[0],即使每個元素只有一個文本節點。這是由于 getElementsByTagName() 方法總是會返回數組。

解析 XML 字符串 - 跨瀏覽器實例

下面的代碼加載并解析一個 XML 字符串:

下面的代碼片段使用 loadXMLString 函數把 books.xml 載入 XML 解析器,并顯示第一個 book 的數據:

text="<bookstore>"
text=text+"<book>";
text=text+"<title>Harry Potter</title>";
text=text+"<author>J K. Rowling</author>";
text=text+"<year>2005</year>";
text=text+"</book>";
text=text+"</bookstore>";
xmlDoc=loadXMLString(text);
document.write(xmlDoc.getElementsByTagName("title")
[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("author")
[0].childNodes[0].nodeValue);
document.write("<br />");
document.write(xmlDoc.getElementsByTagName("year")
[0].childNodes[0].nodeValue);

輸出:

Harry Potter
J K. Rowling
2005

TIY