i want to loop through an XML javascript childNodes dynamically using a for loop, i don't understand why this doesn't work? please take a look at my code - thanks!
XML structure:
<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>
Outputs:
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
Should Output:
len=3
0=
childNodes= 0 - child1
childNodes= 1 - child2
1=
childNodes= 0 - child1
3=
childNodes= 0 - child1
childNodes= 1 - child2
childNodes= 2 - child3
found way around this, heres what i did. hope this helps someone else out there..
Updated 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>
Output:
len=3
0=
childNodes= 0 - child1
childNodes= 1 - child2
1=
childNodes= 0 - child1
2=
childNodes= 0 - child1
childNodes= 1 - child2
childNodes= 2 - child3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.