开发者

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

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

I need to find all开发者_如何学C 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


You can also do:

def xml = new XmlSlurper().parse(file)
def cars = xml.'**'.findAll { it.name() == 'car' }


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜