XML DOM 獲取節點值
nodeValue 屬性用於獲取節點的文字值。
getAttribute() 方法返回屬性的值。
獲取元素的值
在 DOM 中,一切都是節點。元素節點沒有文字值。
元素節點的文字值儲存在一個子節點中。這個節點被稱為文字節點。
要檢索元素的文字值,您必須檢索元素的文字節點的值。
getElementsByTagName 方法
getElementsByTagName() 方法返回一個所有元素的節點列表,這些元素具有指定的標籤名稱,並且按照它們在源文件中出現的順序排列。
假設 books.xml 已經載入到 xmlDoc 中。
此程式碼檢索第一個 <title> 元素
var x = xmlDoc.getElementsByTagName("title")[0];
ChildNodes 屬性
childNodes 屬性返回一個元素的子節點列表。
以下程式碼檢索第一個 <title> 元素的文字節點
x = xmlDoc.getElementsByTagName("title")[0];
y = x.childNodes[0];
nodeValue 屬性
nodeValue 屬性返回文字節點的文字值。
以下程式碼檢索第一個 <title> 元素的文字節點的文字值
示例
x = xmlDoc.getElementsByTagName("title")[0];
y = x.childNodes[0];
z = y.nodeValue;
z 中的結果: "Everyday Italian"
完整示例
示例
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName('title')[0];
var y = x.childNodes[0];
document.getElementById("demo").innerHTML = y.nodeValue;
}
</script>
</body>
</html>
自己動手試一試 »
遍歷所有 <title> 元素:親自嘗試
獲取屬性值
在 DOM 中,屬性是節點。與元素節點不同,屬性節點具有文字值。
獲取屬性值的方法是獲取其文字值。
這可以透過使用 getAttribute() 方法或使用屬性節點的 nodeValue 屬性來完成。
獲取屬性值 - getAttribute()
getAttribute() 方法返回屬性的值。
以下程式碼檢索第一個 <title> 元素的“lang”屬性的文字值
txt 中的結果: "en"
遍歷所有 <book> 元素並獲取它們的“category”屬性:親自嘗試
獲取屬性值 - getAttributeNode()
getAttributeNode() 方法返回一個屬性節點。
以下程式碼檢索第一個 <title> 元素的“lang”屬性的文字值
示例
x = xmlDoc.getElementsByTagName("title")[0];
y = x.getAttributeNode("lang");
txt = y.nodeValue;
自己動手試一試 »
txt 中的結果 = "en"
遍歷所有 <book> 元素並獲取它們的“category”屬性:親自嘗試