如何使用Javascript从XML文档中提取值

问题描述:

我正在尝试从xml文档中提取值并打印它们.我也想计算子节点数(子节点)每个节点都有.即第一个标签有2个孩子,第二个标签有3个孩子.

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 and second tag has 3.

这是XML文档

<?xml version="1.0" ?> 
  <A>
  <a1>a1</a1> 
  <a2>a2</a2> 
  <B>
  <C>2</C> 
  <C>3</C> 
  </B>
  <B>
  <C>4</C> 
  <C>5</C> 
  <C>6</C>
  </B>
  </A>

这是我的私人文档

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","extractexample.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
xmlObj=xmlDoc.documentElement;
document.write(xmlDoc.getElementsByTagName("B")[0].childNodes[0].nodeValue);

Element.childNodes 方法返回所有类型的节点,包括空白文本节点.可能不是您想要的.如果只关心子元素的数量,请使用 childElementCount .

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

我没有在IE中尝试过,它可能无法正常工作.否则,如果需要元素列表,请使用非HTML文档不支持的 children children .您可以尝试使用此功能:

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;