Access XML DOM child nodes by name

I want to access the textContent property of an XML object in JavaScript. The root element has several children who also have some children. To get children at the first level, I just iterate over the childNodes array from the root element. But to get the values โ€‹โ€‹of the "grandchildren", I would like to use something like getElementsByTagName() , which does not work. Currently, I just iterate over all the children and check each nodeName property to get my values. Is there a way to get a child by name?

XML ( Note: The XML document I receive internally is unformatted, no spaces, no #text nodes ):

 <root> <element> <child1>content</child1> <child2>content</child2> <child3>content</child3> </element> <element> <child1>content</child1> <child2>content</child2> <child3>content</child3> </element> </root> 

What I have tried so far:

 xmlDoc = xmlhttp.responseXML; for(i = 0; i < xmlDoc.documentElement.childNodes.length; i++) { key = xmlDoc.documentElement.childNodes[i]; alert(key.getElementsByTagName('child1')[0].textContent); } 

which results in a message: undefined
and console error: TypeError: key.getElementsByTagName (...) [0] - undefined

Browser: Firefox 26

Perhaps this is a problem with the DOM object, I create it as follows:

 var xmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==4 && xmlhttp.status==200) { xmlDoc = xmlhttp.responseXML; 
+6
source share
3 answers

The problem is that the gaps between the nodes are automatically created by textNodes. Make sure the node in xmlDoc.documentElement.childNodes[i] is textNode (nodeType 3) before trying to find children. I also deleted your global variables i and key in this example.

http://jsfiddle.net/GQ8Kd/

 var node, childNodes = xmlDoc.documentElement.childNodes; for(var i = 0; i < childNodes.length; i++) { node = childNodes[i]; if(node.nodeType !== Node.TEXT_NODE) console.log(node.getElementsByTagName('child1')[0].textContent); } 
+3
source

Using the following, you will get the desired value of the child nodes for me.

 var k = xmlDoc.getElementsByTagName("child1"); for(var i = 0; i < k.length; i++) { console.log(k[i].childNodes[0].nodeValue); } 
0
source

Try getElementsByTagName('child1')[0].nodeValue

0
source

All Articles