Get value of an XML attribute with Groovy (gpath)

拜拜、爱过 提交于 2019-12-01 10:45:53

I can't tell if you expect there to be multiple matches or if you know there will be exactly one. The following will find them all and print their answer.

source = '''
<root>
    <foo name = 'type' answer  = 'car'/>
    <foo name = 'color' answer = 'red'/>
    <foo name = 'size' answer = 'big'/>
</root>
'''
xml = new XmlParser().parseText(source)

results = xml.findAll { it.@name == 'type' }

results.each {
    println it.@answer
}

I hope that helps.

EDIT:

If you know there is only one you can do something like this...

println xml.find { it.@name == 'type' }.@answer

Yet another option (you have several):

xml = new XmlParser().parseText(source)

xml.each { 
    if(it.@name == 'type') {
        println it.@answer
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!