1

我想使用 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
4

1 回答 1

0

找到了解决方法,这就是我所做的。希望这对其他人有帮助..

更新的 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;

function RemoveWhitespace(xml){
    var loopIndex;
    for (loopIndex = 0; loopIndex < xml.childNodes.length; loopIndex++) {
        var currentNode = xml.childNodes[loopIndex];
        if (currentNode.nodeType == 1){RemoveWhitespace(currentNode);}
        if (((/^\s+$/.test(currentNode.nodeValue))) && (currentNode.nodeType == 3)){
            xml.removeChild(xml.childNodes[loopIndex--]);
        }
    } 
}

RemoveWhitespace(xmlDoc);

var node = xmlDoc.documentElement.childNodes;
document.write("len="+node.length+"<br>");

for(var i = 0; i < node.length; i++){

    var child = node[i];
    document.write(i+"= <br>");

    for(var j = 0; j < child.getElementsByTagName('child').length; j++){
        document.write("childNodes= "+j+" - "+child.getElementsByTagName('child')[j].textContent+"<br>");
    }
}

</script>

输出:

len=3
0= 
childNodes= 0 - child1
childNodes= 1 - child2
1= 
childNodes= 0 - child1
2= 
childNodes= 0 - child1
childNodes= 1 - child2
childNodes= 2 - child3
于 2015-02-09T02:51:35.197 回答