我有2个相同的,首先:
<!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"。我尝试了很多次,但这不是改变。你能帮我吗???
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>