【问题标题】:How do I parse XML with duplicate nodes?如何解析具有重复节点的 XML?
【发布时间】:2019-02-23 20:51:32
【问题描述】:

这是我的 XML 文件。那里有三个author 节点:

<bookstore>    
  <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>    
</bookstore>

当我使用var author = $(this).find('author'); 时,author 将所有作者保存在一个字符串中。我想把它作为一个数组。有什么办法吗?

var author = $(this).find('author').toArray();

返回长度为 0 的数组

【问题讨论】:

    标签: jquery xml xml-parsing


    【解决方案1】:

    find('author') 将返回一个包含节点集合的 jQuery 对象。因此,您可以使用 each() 循环遍历它们:

    var authors = $(this).find('author');
    authors.each(function() {
      console.log($(this).text());
    });
    

    如果你特别想要一个包含所有值的数组,那么你可以使用map():

    var authors = $(this).find('author').map(function() {
      return $(this).text();
    }).get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多