简体   繁体   中英

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;

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

Using the following obtains the desired value of the child1 nodes for me..

var k = xmlDoc.getElementsByTagName("child1");

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

尝试getElementsByTagName('child1')[0].nodeValue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM