I'm trying to loop over a XMLSlurper find statement using a list array. Can you do this?

StackOverflow https://stackoverflow.com/questions/16255675

  •  13-04-2022
  •  | 
  •  

Question

I'm trying to loop over an expression like this changing the string 'question-hyperlink' to an item in a list I'm new to groovy and can't find a way that works. Do you really have to hard code this ? Every example I can find is hardcoded

.find{ it.@class == 'question-hyperlink'}it.book.title 
Was it helpful?

Solution

No need to be hardcoded, you can use a list and you can use the in operator:

xml = '''<div>
    <div class="header">header div</div>
    <div class="body">body div</div>
    <span class="footer">footer span</span>
</div>
'''

node = new XmlSlurper().parseText xml

// the element's classes we want
classes = ['header', 'body']

contents = node.breadthFirst().findAll { it.@class in classes }*.text()

assert contents == ['header div', 'body div']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top