XML DOM childNodes 属性

定义和用法

childNodes 属性返回包含所选节点的子节点的 NodeList。

如果所选节点没有子节点,则此属性返回不包含节点的 NodeList。

提示:如需循环遍历 childNodes 列表,使用 nextSibling 属性比显式使用父对象的 childNodes 列表更有效。

语法

elementNode.childNodes

实例

例子 1

以下代码将 "books.xml" 加载到 xmlDoc 中,并从 "books.xml" 中的第一个 <title> 元素获取文本节点:

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;
{}

Try It Yourself

例子 2

以下代码将 "books.xml" 加载到 xmlDoc 中,并从 "books.xml" 中的第一个 <book> 元素获取子节点的数量:
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("book")[0].childNodes;
    document.getElementById("demo").innerHTML =
    x.length;
{}

Try It Yourself

Firefox and most other browsers will treat whitespace or line breaks as text nodes, while Internet Explorer will not. Therefore, the output will be different in the above example.

For more information on the differences between browsers, please visit the DOM Browser section in the XML DOM tutorial.