【问题标题】:The length of childNodes XML [closed]childNodes XML的长度[关闭]
【发布时间】:2016-06-27 12:31:20
【问题描述】:

我有两个一样的,第一:

<!DOCTYPE html>
<html>
<body>
    <p id="demo"></p>
    <script>
        var x, i, xmlDoc;
        var txt = "";
        var text = "<book>" + 
        "<title>Everyday Italian</title>" +
        "<author>Giada De Laurentiis</author>" +
        "<year>2005</year>" +
        "</book>";
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(text,"text/xml");
        x = xmlDoc.documentElement.childNodes;
        document.write(x.length);
    </script>
</body>
</html>

第二个文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DOM XML</title>
    <script language = "javascript" type = "text/javascript">
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function(){
            if(xhttp.readyState == 4 && xhttp.status == 200){
                xmlDoc = xhttp.responseXML;
                x = xmlDoc.documentElement.childNodes;
                document.write(x.length);
            }   
        };
        xhttp.open('get','book3.xml',true);
        xhttp.send();
    </script>
</head>
<body>

</body>
</html>

还有 book3.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<book>
    <title>Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
</book>

我认为第一个代码中的文本变量与 book3.xml 中的代码相同,但是当我打印 x.length 时,顶部的结果是“3”,下面的结果是“7”。我尝试了很多次,但它没有改变。你能帮我解释一下原因吗???

【问题讨论】:

    标签: javascript php jquery xml dom


    【解决方案1】:

    您的 xml 文件有 4 个文本节点,它们是 &lt;book&gt; 元素的子节点。标签之间的所有空白构成了这些文本节点。在您的 js 字符串中,没有空格

    <?xml version="1.0" encoding="UTF-8"?>
    <book><!--  child node 1
     --><title>Everyday Italian</title><!--  child node 3
     --><author>Giada De Laurentiis</author><!--  child node 5
     --><year>2005</year><!--  child node 7 -->
    </book>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      相关资源
      最近更新 更多