XML DOM 獲取節點值

nodeValue 屬性用于獲取節點的文本值。

getAttribute() 方法返回屬性的值。

實例

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

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

獲取元素的值
本例使用 getElementsByTagname() 獲取 "books.xml" 中第一個 <title> 元素。
獲取屬性的值
本例使用 getAttribute() 方法獲取 "books.xml" 中第一個 <title> 元素的 "lang" 屬性的值。

獲取元素的值

在 DOM 中,每種成分都是節點。元素節點沒有文本值。

元素節點的文本存儲在子節點中。該節點稱為文本節點。

獲取元素文本的方法,就是獲取這個子節點(文本節點)的值。

獲取元素值

getElementsByTagName() 方法返回包含擁有指定標簽名的所有元素的節點列表,其中的元素的順序是它們在源文檔中出現的順序。

下面的代碼通過使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中,并檢索第一個 <title> 元素:

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0];

childNodes 屬性返回子節點的列表。<title> 元素只有一個子節點,即一個文本節點。

下面的代碼檢索 <title> 元素的文本節點:

x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];

nodeValue 屬性返回文本節點的文本值:

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

結果:txt = "Harry Potter"

TIY

遍歷所有 <title> 元素:TIY

獲取屬性的值

在 DOM 中,屬性也是節點。與元素節點不同,屬性節點擁有文本值。

獲取屬性的值的方法,就是獲取它的文本值。

可以通過使用 getAttribute() 方法或屬性節點的 nodeValue 屬性來完成這個任務。

獲取屬性值 - getAttribute()

getAttribute() 方法返回屬性的值。

下面的代碼檢索第一個 <title> 元素的 "lang" 屬性的文本值:

xmlDoc=loadXMLDoc("books.xml");
txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");

結果:txt = "en"

例子解釋:

  • 通過使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中
  • 把 txt 變量設置為第一個 title 元素節點的 "lang" 屬性的值

TIY

遍歷所有 <book> 元素,并獲取它們的 "category" 屬性:TIY

獲取屬性值 - getAttributeNode()

getAttributeNode() 方法返回屬性節點。

下面代碼檢索第一個 <title> 元素的 "lang" 屬性的文本值:

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.getElementsByTagName("title")[0].getAttributeNode("lang");
txt=x.nodeValue;

結果:txt = "en"

例子解釋:

  • 通過使用 loadXMLDoc() 把 "books.xml" 載入 xmlDoc 中
  • 獲取第一個 <title> 元素節點的 "lang" 屬性節點
  • 把 txt 變量設置為屬性的值

TIY

循環所有 <book> 元素并獲取它們的 "category" 屬性:TIY