尝试从 XML 中提取时无法选择子项 - 在本例中为作者:
<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
我无法获取 javascript 脚本来显示我选择的作者。意思是如果我这样做。
txt=xmlDoc.getElementsByTagName("title")[2].childNodes[0].nodeValue;
document.write("<p>"+txt);
我得到“詹姆斯·麦戈文”。但是
txt=xmlDoc.getElementsByTagName("title")[2].childNodes[1].nodeValue;
document.write("<p>"+txt);
不会给我“Per Bothner”。我怎样才能使这成为可能?
最佳答案
虽然我也想知道您是如何获得结果的……childNodes
数组不仅包含元素,而且(除其他外)还包含文本节点,即行分隔符 (CR/LF) .因此,您必须遍历数组以检查每个条目的节点类型。更好的选择是使用 xpath 来选择有趣的元素,this article应该让你开始。
具体来说,/book/author
将按文档顺序准确选择 author
节点。
关于javascript - 子节点多个javascript XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14266760/