I开发者_开发问答 am trying to extract values from the xml document and print them. I also want to count the number of children(child nodes) each node has.That is the first tag has 2 child and second tag has 3.
THIS IS THE XML DOCUMENT
<?xml version="1.0" ?>
<A>
<a1>a1</a1>
<a2>a2</a2>
<B>
<C>2</C>
<C>3</C>
</B>
<B>
<C>4</C>
<C>5</C>
<C>6</C>
</B>
</A>
THIS IS MY JAVASCRIPT DOCUMENT
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","extractexample.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
xmlObj=xmlDoc.documentElement;
document.write(xmlDoc.getElementsByTagName("B")[0].childNodes[0].nodeValue);
Element.childNodes
method returns all types of nodes, including whitespace textnodes. It may not be what you want. If you only care for the number of child elements, use childElementCount
.
var b = xmlDoc.getElementsByTagName("B")[0];
alert(b.childElementCount); //should output 2
I haven't tried in IE, it may not work.
Else, if you want a the element list, use children
children
not supported on non HTML doc. You can try this function:
function getChildren(element) {
var nodes = element.childNodes;
var children = [];
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].nodeType == Node.ELEMENT_NODE) children.push(nodes[i]);
}
return children;
}
getChildren(b).length;
精彩评论