Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  21] [ 4]  / answers: 1 / hits: 37647  / 11 Years ago, tue, january 28, 2014, 12:00:00

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;

More From » xml

 Answers
18

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);
}

[#72892] Monday, January 27, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mattieparisp

Total Points: 612
Total Questions: 109
Total Answers: 104

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
;