childNodes XML的长度[关闭]
Posted
技术标签:
【中文标题】childNodes XML的长度[关闭]【英文标题】:The length of childNodes XML [closed] 【发布时间】: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”。我尝试了很多次,但它没有改变。你能帮我解释一下原因吗???
【问题讨论】:
【参考方案1】:您的 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>
【讨论】:
以上是关于childNodes XML的长度[关闭]的主要内容,如果未能解决你的问题,请参考以下文章
xml http://stackoverflow.com/questions/38980559/xquery-test-for-two-specific-children-with-and/38980
xml http://stackoverflow.com/questions/38980559/xquery-test-for-two-specific-children-with-and/38980