jquery - 如何解析具有重复节点的 XML?
问题描述
这是我的 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 的数组
解决方案
将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();