我正在尝试迭代几个XML文件来比较它们中的数据。 (大数据样本)。 由于项目设置,我宁愿在groovy脚本中这样做。
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>
如何迭代所有'端点'子元素?
请记住,我有一个非常大的数据样本,并且更喜欢有点标准化的解决方案。因为我必须经历许多不同类型的子元素。
答案 0 :(得分:1)
你可以像这样进行深度优先搜索:
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()}"
}