how to extract values from an XML document using Javascript

前端 未结 1 658
失恋的感觉
失恋的感觉 2020-12-12 07:29

I am trying to extract values from the xml document and print them. I also want to count the number of children(child nodes) each node has.That is the first tag has 2 child

相关标签:
1条回答
  • 2020-12-12 07:45

    Element.childNodes method returns all types of nodes, including whitespace textnodes. It may not be what you want. If you only care for the number of child elements, use childElementCount.

    var b = xmlDoc.getElementsByTagName("B")[0];
    alert(b.childElementCount); //should output 2
    

    I haven't tried in IE, it may not work. Else, if you want a the element list, use children children not supported on non HTML doc. You can try this function:

    function getChildren(element) {
      var nodes = element.childNodes;
      var children = [];
      for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].nodeType == Node.ELEMENT_NODE) children.push(nodes[i]);
      }
      return children;
    }
    
    getChildren(b).length;
    
    0 讨论(0)
提交回复
热议问题