How to find all XML elements by tag name in Groovy?

前端 未结 3 957
一个人的身影
一个人的身影 2020-12-14 19:25

How I can find all elements in XML by their tag name in Groovy (GPath)?

I need to find all car elements in this document:



        
相关标签:
3条回答
  • 2020-12-14 19:45

    This is how it works:

    def xml = new XmlSlurper().parse(file)
    def cars = xml.depthFirst().findAll { it.name() == 'car' }
    assert cars.size() == 2
    
    0 讨论(0)
  • 2020-12-14 19:48

    You can also do:

    def xml = new XmlSlurper().parse(file)
    def cars = xml.'**'.findAll { it.name() == 'car' }
    
    0 讨论(0)
  • 2020-12-14 19:48

    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*/
    
    0 讨论(0)
提交回复
热议问题