XML DOM - 屬性和方法
屬性和方法向 XML DOM 定義了編程接口。
實(shí)例
下面的例子使用 XML 文件 books.xml。
函數(shù) loadXMLDoc(),位于外部 JavaScript 中,用于加載 XML 文件。
函數(shù) loadXMLString(),位于外部 JavaScript 中,用于加載 XML 字符串。
編程接口
DOM 把 XML 模擬為一系列節(jié)點(diǎn)接口。可通過(guò) JavaScript 或其他編程語(yǔ)言來(lái)訪問(wèn)節(jié)點(diǎn)。在本教程中,我們使用 JavaScript。
對(duì) DOM 的編程接口是通過(guò)一套標(biāo)準(zhǔn)的屬性和方法來(lái)定義的。
屬性經(jīng)常按照“某事物是什么”的方式來(lái)使用(例如節(jié)點(diǎn)名是 "book")。
方法經(jīng)常按照“對(duì)某事物做什么”的方式來(lái)使用(例如刪除 "book" 節(jié)點(diǎn))。
XML DOM 屬性
一些典型的 DOM 屬性:
- x.nodeName - x 的名稱
- x.nodeValue - x 的值
- x.parentNode - x 的父節(jié)點(diǎn)
- x.childNodes - x 的子節(jié)點(diǎn)
- x.attributes - x 的屬性節(jié)點(diǎn)
注釋:在上面的列表中,x 是一個(gè)節(jié)點(diǎn)對(duì)象。
XML DOM 方法
- x.getElementsByTagName(name) - 獲取帶有指定標(biāo)簽名稱的所有元素
- x.appendChild(node) - 向 x 插入子節(jié)點(diǎn)
- x.removeChild(node) - 從 x 刪除子節(jié)點(diǎn)
注釋:在上面的列表中,x 是一個(gè)節(jié)點(diǎn)對(duì)象。
實(shí)例
從 books.xml 中的 <title> 元素獲取文本的 JavaScript 代碼:
txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue
在此語(yǔ)句執(zhí)行后,txt 保存的值是 "Harry Potter"。
解釋:
- xmlDoc - 由解析器創(chuàng)建的 XML DOM
- getElementsByTagName("title")[0] - 第一個(gè) <title> 元素
- childNodes[0] - <title> 元素的第一個(gè)子節(jié)點(diǎn) (文本節(jié)點(diǎn))
- nodeValue - 節(jié)點(diǎn)的值 (文本自身)
在上面的例子中,getElementsByTagName 是方法,而 childNodes 和 nodeValue 是屬性。
解析 XML 文件 - 跨瀏覽器實(shí)例
下面的代碼片段使用 loadXMLDoc 函數(shù)把 books.xml 載入 XML 解析器中,并顯示第一個(gè) book 的數(shù)據(jù):
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
在上面的例子中,我們?yōu)槊總(gè)文本節(jié)點(diǎn)使用 childNodes[0],即使每個(gè)元素只有一個(gè)文本節(jié)點(diǎn)。這是由于 getElementsByTagName() 方法總是會(huì)返回?cái)?shù)組。
解析 XML 字符串 - 跨瀏覽器實(shí)例
下面的代碼加載并解析一個(gè) XML 字符串:
下面的代碼片段使用 loadXMLString 函數(shù)把 books.xml 載入 XML 解析器,并顯示第一個(gè) book 的數(shù)據(jù):
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