How to extract values ​​from an XML document using Javascript

I am trying to extract values ​​from an xml document and print them. I also want to count the number of children (child nodes) each node has. This is the first tag with 2 child tags and the second tag with 3.

THIS IS AN 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); 
0
source share
1 answer

Element.childNodes returns all types of nodes, including text fields as spaces. Perhaps this is not what you want. If you only care about the number of children, use childElementCount .

 var b = xmlDoc.getElementsByTagName("B")[0]; alert(b.childElementCount); //should output 2 

I have not tried in IE, it may not work. Otherwise, if you need a list of elements, use children children , which are not supported in a non-HTML document. 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; 
+2
source

All Articles