childNodes XML

时间:2016-03-12 05:31:58

标签: javascript php jquery xml dom

  

我有两个相同,第一:

<!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时,顶部的结果是&#34; 3&#34;以下是&#34; 7&#34;。我尝试了很多次,但没有改变。你能帮助我吗???

1 个答案:

答案 0 :(得分:-2)

您的xml文件有4个文本节点,它们是<book>元素的子节点。标签之间的所有空格构成了这些文本节点。在你的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>