简体   繁体   中英

how to iterate through xml file in groovy script

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.

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()}"
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM