我想使用 for 循环动态循环通过 XML javascript childNodes,我不明白为什么这不起作用?请看看我的代码 - 谢谢!
XML结构:
<data>
<node>
<child>child1</child>
<child>child2</child>
</node>
<node>
<child>child1</child>
</node>
<node>
<child>child1</child>
<child>child2</child>
<child>child3</child>
</node>
</data>
Javascript:
<script>
if (window.XMLHttpRequest){
xhttp=new XMLHttpRequest();
}else{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","data.xml",false);
xhttp.send();
xmlDoc= xhttp.responseXML;
var node = xmlDoc.getElementsByTagName("node");
var child = xmlDoc.getElementsByTagName("child");
document.write("len="+node.length+"<br>");
for ( var i = 0; i < node.length ; i++ ){
document.write(""+i+"=<br>");
for ( var j = 0; j < child.length ; j++ ){
document.write("childNodes= "+j+" - "+child[j].childNodes[0].nodeValue+"<br>");
}
}
</script>
输出:
len=3
0=
childNodes= 0 - child1
childNodes= 1 - child2
childNodes= 2 - child1
childNodes= 3 - child1
childNodes= 4 - child2
childNodes= 5 - child3
1=
childNodes= 0 - child1
childNodes= 1 - child2
childNodes= 2 - child1
childNodes= 3 - child1
childNodes= 4 - child2
childNodes= 5 - child3
2=
childNodes= 0 - child1
childNodes= 1 - child2
childNodes= 2 - child1
childNodes= 3 - child1
childNodes= 4 - child2
childNodes= 5 - child3
应该输出:
len=3
0=
childNodes= 0 - child1
childNodes= 1 - child2
1=
childNodes= 0 - child1
3=
childNodes= 0 - child1
childNodes= 1 - child2
childNodes= 2 - child3