Accessing XML DOM child nodes by name

33,510

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);
}
Share:
33,510
robin.koch
Author by

robin.koch

Updated on January 29, 2020

Comments

  • robin.koch
    robin.koch over 4 years

    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;