Groovy - XmlSlurper - find innermost element

2019-08-08 20:23发布

I have the following xml:

<vehicle>
  <car>
    <price>100</price>
    <price>200</price>
  </car>
  <car>
    <price>300</price>
    <price>400</price>
  </car>
</vehicle>

Given an xml, how can we get the innermost elements (in this case, all the<price> elements)?

3条回答
The star\"
2楼-- · 2019-08-08 21:05

Assuming you have the xml in a String xml, you should be able to do:

List prices = new XmlSlurper().parseText( xml ).car.price*.text()​​
查看更多
我命由我不由天
3楼-- · 2019-08-08 21:07

May I suggest you next variant:

def vehicle = new XmlSlurper().parseText(xmlString)
vehicle.car.price.each {println "car's price:"+it}
查看更多
Explosion°爆炸
4楼-- · 2019-08-08 21:12

thanks Tim for the answer. I just figured out the following works too. And is more generic:

def document = slurper.parseText(xml)
def prices = document.'**'.findAll { it.children().size() == 0 }
查看更多
登录 后发表回答