xml的示例:
<response version-api="2.0">
<value>
<books>
<book available="20" id="1" tags="">
<title>Don Xijote</title>
<author id="1" tags="Joel">Manuel De Cervantes</author>
</book>
<book available="14" id="2" tags"Jane">
<title>Catcher in the Rye</title>
<author id="2" tags="">JD Salinger</author>
</book>
<book available="13" id="3" tags="">
<title>Alice in Wonderland</title>
<author id="3">Lewis Carroll</author>
</book>
<book available="5" id="4" tags="Harry">
<title>Don Xijote</title>
<author id="4">Manuel De Cervantes</author>
</book>
</books>
</value>
</response>
基本上,我试图将我选择的字符串值附加到称为“标签”的所有属性中。这就是“标签”属性是否具有值,以及这些属性是否在xml结构的不同级别。我已经尝试了方法appendNode(),但它又返回了一个时髦的运行时表达式错误。我也查看了这个stackoverflow question,但是我离我所需的答案越来越近了。这是代码:
def rootFolder = new File('.').getCanonicalPath()
def response = new XmlSlurper().parse(new File(rootFolder + File.separator + 'src' + File.separator + 'metadata.xml'))
def tags = response.'**'.findAll { it['@tags']!='' }
tags.each{ t ->
def tagAttr = (t.@tags.value.toString())
println(tagAttr)
}
有人对我如何实现这一目标有任何想法吗?
最佳答案
您差点儿明白了...这应该做您想要的(假设我握住了棍子的右端):
def xml = '''<response version-api="2.0">
| <value>
| <books>
| <book available="20" id="1" tags="">
| <title>Don Xijote</title>
| <author id="1" tags="Joel">Manuel De Cervantes</author>
| </book>
| <book available="14" id="2" tags="Jane">
| <title>Catcher in the Rye</title>
| <author id="2" tags="">JD Salinger</author>
| </book>
| <book available="13" id="3" tags="">
| <title>Alice in Wonderland</title>
| <author id="3">Lewis Carroll</author>
| </book>
| <book available="5" id="4" tags="Harry">
| <title>Don Xijote</title>
| <author id="4">Manuel De Cervantes</author>
| </book>
| </books>
| </value>
|</response>'''.stripMargin()
import groovy.xml.*
def parsed = new XmlParser().parseText(xml)
parsed.'**'
.findAll { 'tags' in it.attributes().keySet().toList() }
.each { it.@tags += (it.@tags ? ' ' : '') + 'extraTag' }
println XmlUtil.serialize(parsed)
关于xml - 使用Groovy附加到xml文件的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32914254/