Accessing XML DOM child nodes by name

后端 未结 3 1974
萌比男神i
萌比男神i 2021-01-05 10:42

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

相关标签:
3条回答
  • 2021-01-05 11:19

    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);
    }
    
    0 讨论(0)
  • 2021-01-05 11:31

    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);
    }
    
    0 讨论(0)
  • 2021-01-05 11:38

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

    0 讨论(0)
提交回复
热议问题