如何在 Groovy 中按标签名称查找所有 XML 元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6726592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 14:50:55 来源:igfitidea点击:
How to find all XML elements by tag name in Groovy?
提问by yegor256
How I can find all elements in XML by their tag name in Groovy (GPath)?
如何通过 Groovy (GPath) 中的标记名称查找 XML 中的所有元素?
I need to find all carelements in this document:
我需要car在此文档中找到所有元素:
<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
回答by yegor256
This is how it works:
这是它的工作原理:
def xml = new XmlSlurper().parse(file)
def cars = xml.depthFirst().findAll { it.name() == 'car' }
assert cars.size() == 2
回答by tim_yates
You can also do:
你也可以这样做:
def xml = new XmlSlurper().parse(file)
def cars = xml.'**'.findAll { it.name() == 'car' }
回答by Igor
Use an XMLSlurper
def records = new XmlSlurper().parseText(file)
reco?rds.depthFirst()?.findAll { !it.childNodes() && it.car} ?
/*Otherwise this returns the values for parent nodes as well*/

