Groovy - XmlSlurper - find innermost element

青春壹個敷衍的年華 提交于 2020-01-06 03:16:04

问题


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)?


回答1:


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

List prices = new XmlSlurper().parseText( xml ).car.price*.text()​​



回答2:


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 }



回答3:


May I suggest you next variant:

def vehicle = new XmlSlurper().parseText(xmlString)
vehicle.car.price.each {println "car's price:"+it}


来源:https://stackoverflow.com/questions/23632849/groovy-xmlslurper-find-innermost-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!