Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing XML DOM child nodes by name

I want to access the textContent property of an XML object in JavaScript. The root item has several children which also have some children themselves. To get the children on the first level I just iterate through the childNodes Array of the root element. But to get the values of the "grandchilds" I would like to use something like getElementsByTagName(), which doesn't work. Currently I just iterate through all children again and check the nodeName property of each to get my values. Is there a way to get the child object by name?

XML (Notice: the XML document I get internally is unformatted, there are no whitespaces, there are 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 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 an message box: undefined
and an console error: TypeError: key.getElementsByTagName(...)[0] is undefined

Browser: Firefox 26

Maybe it's a problem with the DOM Object, I create it the following way:

var xmlhttp;
if (window.XMLHttpRequest)
{
  xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
  if(xmlhttp.readyState==4 && xmlhttp.status==200)
  {
    xmlDoc = xmlhttp.responseXML;
like image 465
robin.koch Avatar asked Jan 28 '14 13:01

robin.koch


1 Answers

The problem is the spaces between the nodes are automatically made textNodes. Check if the node at xmlDoc.documentElement.childNodes[i] is a textNode (nodeType 3) before you try to find children. I also removed your globals 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);
}
like image 141
megawac Avatar answered Oct 03 '22 00:10

megawac