【问题标题】:XML Parsing Root Node with JavaScript使用 JavaScript 解析 XML 根节点
【发布时间】:2015-03-20 12:26:33
【问题描述】:

我有这个 XML 文件。我想用 Javascript 解析它以仅获取根节点中的 Example1Example2 。如果我使用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>

【问题讨论】:

  • document.querySelectorAll("bookstore &gt; author").

标签: javascript xml parsing


【解决方案1】:

您可以使用 document.querySelectorAll('bookstore &gt; author') 作为 cmets 中建议的 @Phylogenesis。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 2012-06-09
    • 1970-01-01
    相关资源
    最近更新 更多