如何在Groovy中通过标签名称查找所有XML元素?
问题描述:
我需要找到所有 car
How I can find all elements in XML by their tag name in Groovy (GPath)?
如何通过Groovy(GPath)中的标签名称找到XML中的所有元素?
I need to find all car
elements in this document:
<records>
<first>
<car>
<id>378932</id>
</car>
</first>
<second>
<foo>
<car>
<name>audi</name>
</car>
</foo>
</second>
</records>
这是我试过的和失败的:
This is what I tried and failed:
def xml = new XmlSlurper().parse(file)
assert xml.car.size() == 2
答
这是如何工作的:
This is how it works:
def xml = new XmlSlurper().parse(file)
def cars = xml.depthFirst().findAll { it.name() == 'car' }
assert cars.size() == 2