如何使用 Javascript 从 XML 文档中提取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5415452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to extract values from an XML document using Javascript
提问by swati gupta
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 文档中提取值并打印它们。我还想计算每个节点的子节点(子节点)的数量。也就是说,第一个标签有 2 个子节点,第二个标签有 3 个。
THIS IS THE XML DOCUMENT
这是 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>
THIS IS MY JAVASCRIPT DOCUMENT
这是我的 JAVASCRIPT 文档
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);
回答by syockit
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
.
Element.childNodes
方法返回所有类型的节点,包括空白文本节点。它可能不是您想要的。如果您只关心子元素的数量,请使用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:
我没有在 IE 中尝试过,它可能不起作用。
否则,如果您想要元素列表,请children
children
在非 HTML 文档上使用不支持。你可以试试这个功能:
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;