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 中的结果:雅舍谈吃

完整实例

Esempio 1

<!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>

Prova da solo

Esempio 2

Eseguire un ciclo di scansione su tutti gli elementi <title>:

x = xmlDoc.getElementsByTagName('title');
for (i = 0; i < x.length; i++) { 
    txt += x[i].childNodes[0].nodeValue + "<br>";
}

Prova da solo

Ottieni valore attributo

Nel DOM, gli attributi sono anche nodi. A differenza dei nodi elemento, i nodi attributo hanno un valore di testo.

Il metodo per ottenere il valore dell'attributo è ottenere il valore del testo.

Può essere ottenuto utilizzando getAttribute() Il metodo o il nodo attributo nodeValue Eseguire questa operazione tramite l'attributo.

Ottieni valore attributo - getAttribute()

getAttribute() Il metodo restituisceIl valore dell'attributo.

Il seguente codice ricerca il primo elemento <title>: "lang" Il valore testuale dell'attributo:

Esempio 1

x = xmlDoc.getElementsByTagName("title")[0];
txt = x.getAttribute("lang");

Prova da solo

Esempio 2

Eseguire un ciclo di scansione su tutti gli elementi <book> e ottenere il loro attributo "category":

x = xmlDoc.getElementsByTagName("book");
for (i = 0; i < x.length; i++) { 
    txt += x[i].getAttribute("category") + "<br>";
}

Prova da solo

Ottieni valore attributo - getAttributeNode()

getAttributeNode() Il metodo restituisceIl nodo attributo.

Il seguente codice ricerca il primo elemento <title>: "lang" Il valore testuale dell'attributo:

Esempio 1

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

Prova da solo

Esempio 2

Eseguire un ciclo di scansione su tutti gli elementi <book> e ottenere il loro attributo "category":

x = xmlDoc.getElementsByTagName("book");
for (i = 0; i < x.length; i++) {
    txt += x[i].getAttributeNode("category").nodeValue + "<br>";
}

Prova da solo