XML使用JavaScript解析根节点

时间:2015-03-20 12:26:34

标签: javascript xml parsing

我有这个XML文件。我想解析它以获得根节点中的 Example1 Example2 ,使用Javascript。如果我使用getElementsByTagName('author'),我输出所有作者的值。我该怎么办?

<?xml version='1.0'?>
<bookstore>
  <author>Example1</author>
  <author>Example2</author>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <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>
  <book category="web" cover="paperback">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

1 个答案:

答案 0 :(得分:0)

您可以在评论中使用document.querySelectorAll('bookstore > author') @Phylogenesis。

或者您可以查看parentNodeparentElement属性,例如

var authors = document.getElementsByTagName('author');
for (var i = 0; i < authors.length; ++i) {
    if (authors[i].parentNode == 'bookstore') {
        // process author
    }
}