使用Groovy(gpath)获取XML属性的值 [英] Get value of an XML attribute with Groovy (gpath)
本文介绍了使用Groovy(gpath)获取XML属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在groovy中使用XmlParser()。
请参阅以下代码。当 name 的值是 type 时,我需要打印 answer 的值。
< root>
< foo name ='type'answer ='car'/>
< foo name ='color'answer ='red'/>
< foo name ='size'answer ='big'/>
< / root>
我需要这样做:
def XML = new XmlParser()。parseText(XMLstring)
println XML.root.foo。[where @name ='type']。@ answer
解决方案
我无法分辨您是否期望存在多个匹配或if你知道会有一个。以下将找到他们并打印他们的答案。
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
}
我希望有帮助。
编辑: 如果您知道存在只有一个你可以这样做...
。@ answer另一个选项(您有几个):
xml = new XmlParser()。parseText(source)
xml.each {
if(it。@ name == 'type'){
println it。@ answer
}
}
Using XmlParser() in groovy. See the following code. I need to print the value of answer when the value of name is type.
<root>
<foo name = 'type' answer = 'car'/>
<foo name = 'color' answer = 'red'/>
<foo name = 'size' answer = 'big'/>
</root>
I need to do something like this:
def XML = new XmlParser().parseText(XMLstring)
println XML.root.foo.[where @name = 'type'].@answer
解决方案
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
}
}
这篇关于使用Groovy(gpath)获取XML属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文