我找到一个以查找节点索引的方式处理xml的好方法有问题。例如:
String test = '''
<Library>
<Books>
<Book>
<Title>Hello</Title>
<Author>John Doe</Author>
<Publication>2008</Publication>
</Book>
<Book>
<Title>Bye</Title>
<Author>Mary Derp</Author>
<Publication>2011</Publication>
</Book>
[...]
</Books>
</Library>'''
def xml = new XmlSlurper().parseText(test)
现在我想知道是否有任何书的标题是&#34;再见&#34;而作者是#34; Mary Derp&#34;。如果是,它应该告诉我节点的索引。所以在这种情况下节点[1]。
答案 0 :(得分:1)
&#39;实测&#39;将包含匹配书籍的索引列表:
String test = '''
<Library>
<Books>
<Book>
<Title>Hello</Title>
<Author>John Doe</Author>
<Publication>2008</Publication>
</Book>
<Book>
<Title>Bye</Title>
<Author>Mary Derp</Author>
<Publication>2011</Publication>
</Book>
<Book>
<Title>Hello</Title>
<Author>Mary Derp</Author>
<Publication>2012</Publication>
</Book>
<Book>
<Title>Bye</Title>
<Author>Mary Derp</Author>
<Publication>2012</Publication>
</Book>
</Books>
</Library>'''
def found = []
def Library = new XmlSlurper().parseText(test)
Library.Books.Book.eachWithIndex { def book, int i ->
if (book.Title == 'Bye' && book.Author == 'Mary Derp') {
found += i
}
}
println found
所以在这种情况下它会返回: [1,3]
答案 1 :(得分:1)
请考虑以下事项。它将书籍映射到布尔值(通过collect
),然后找到第一个true
值。 (修改:简化)
def Library = new XmlSlurper().parseText(test)
def index = Library.Books.Book.collect {
(it.Title == 'Bye' && it.Author == 'Mary Derp')
}.indexOf(true)
assert 1 == index