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 中的结果:雅舍谈吃
完整实例
ตัวอย่าง 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>
ตัวอย่าง 2
ลูปเล่นโซ่ทั้งหมดของ <title> อิเล็มนต์:
x = xmlDoc.getElementsByTagName('title'); for (i = 0; i < x.length; i++) { txt += x[i].childNodes[0].nodeValue + "<br>"; {}
ดึงค่าคุณสมบัติ
ใน DOM คุณสมบัติก็เป็นตัวแทนของเครื่องมือ。ต่างจากตัวแทนของอิเล็มนต์ ตัวแทนคุณสมบัติมีค่าข้อความ。
วิธีที่ดึงค่าคุณสมบัติคือดึงค่าข้อความของมัน。
สามารถทำได้โดยใช้ getAttribute()
วิธีหรือคุณสมบัติของตัวแทนคุณสมบัติ nodeValue
คุณสมบัติเพื่อทำงานนี้。
ดึงค่าคุณสมบัติ - getAttribute()
getAttribute()
วิธีที่กลับค่าค่าของคุณสมบัติ。
รหัสใต้นี้ตรวจหาคุณสมบัติของ <title> อิเล็มนต์แรก: "lang"
ค่าของคุณสมบัติข้อความ:
ตัวอย่าง 1
x = xmlDoc.getElementsByTagName("title")[0]; txt = x.getAttribute("lang");
ตัวอย่าง 2
ลูปเล่นโซ่ทั้งหมดของ <book> อิเล็มนต์และดึงคุณสมบัติ "category" ของมัน:
x = xmlDoc.getElementsByTagName("book"); for (i = 0; i < x.length; i++) { txt += x[i].getAttribute("category") + "<br>"; {}
ดึงค่าคุณสมบัติ - getAttributeNode()
getAttributeNode()
วิธีที่กลับค่าตัวแทนของคุณสมบัติ。
รหัสใต้นี้ตรวจหาคุณสมบัติของ <title> อิเล็มนต์แรก: "lang"
ค่าของคุณสมบัติข้อความ:
ตัวอย่าง 1
x = xmlDoc.getElementsByTagName("title")[0]; y = x.getAttributeNode("lang"); txt = y.nodeValue;
ตัวอย่าง 2
ลูปเล่นโซ่ทั้งหมดของ <book> อิเล็มนต์และดึงคุณสมบัติ "category" ของมัน:
x = xmlDoc.getElementsByTagName("book"); for (i = 0; i < x.length; i++) { txt += x[i].getAttributeNode("category").nodeValue + "<br>"; {}