1

I have a problem with finding a good method to handle a xml in a way of finding the index of a node. Example:

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)

Now I want to know if there is any book where the title is "Bye" and the author is "Mary Derp". And if true it should tell me the index of the node. So in this case node[1].

Justin Holze
  • 181
  • 1
  • 2
  • 11

2 Answers2

1

'found' will contain a list of indexes of matching books:

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

So in this case it returns: [1, 3]

askucins
  • 93
  • 7
1

Consider the following. It maps books to booleans (via collect), and then finds the first true value. (Edit: simplified)

def Library = new XmlSlurper().parseText(test)

def index = Library.Books.Book.collect {
    (it.Title == 'Bye' && it.Author == 'Mary Derp')
}.indexOf(true)

assert 1 == index
Michael Easter
  • 23,733
  • 7
  • 76
  • 107