Reputation: 2445
I am trying to iterate through several XML files to compare the data in them. (large data sample). I would prefer to do this in a groovy script because of the project setup.
The XML layout is something like this: (fake data)
<service name='name' pattern='something' isReliable='maybe'>
<receiver name='name' isUsingTwoWaySsl='maybe' isWsRmDisabled='maybe' targetedByTransformation='maybe'>
<endpoint name='local_tst01'>URL</endpoint>
<endpoint name='local_tst02'>URL</endpoint>
<endpoint name='local_tst03'>URL</endpoint>
<environment name='dev' default='local_dev' />
<environment name='tst01' default='test' />
<environment name='tst02' default='local_tst02' />
</receiver>
<operation name='name'>
<sender>sender</sender>
<attribute name='operation' type='String'>name</attribute>
</operation>
</service>
How do i iterate through, for example, all the 'endpoint' child elements?
keep in mind that I have a very large data sample, and prefer a somewhat standardised solution for this. As I have to go through a lot of different types of child elements.
Upvotes: 1
Views: 3343
Reputation: 171074
You can do a depth-first search like so:
def xml = '''<service name='name' pattern='something' isReliable='maybe'>
<receiver name='name' isUsingTwoWaySsl='maybe' isWsRmDisabled='maybe' targetedByTransformation='maybe'>
<endpoint name='local_tst01'>URL</endpoint>
<endpoint name='local_tst02'>URL</endpoint>
<endpoint name='local_tst03'>URL</endpoint>
<environment name='dev' default='local_dev' />
<environment name='tst01' default='test' />
<environment name='tst02' default='local_tst02' />
</receiver>
<operation name='name'>
<sender>sender</sender>
<attribute name='operation' type='String'>name</attribute>
</operation>
</service>'''
new XmlSlurper().parseText(xml)
.'**'
.findAll { it.name() == 'endpoint' }
.each { node ->
println "Found node with attributes ${node.attributes()} and body ${node.text()}"
}
Upvotes: 2