javascript xml循环childNodes

时间:2015-02-09 00:31:04

标签: javascript xml loops child-nodes

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

1 个答案:

答案 0 :(得分: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