I'm newbie in Groovy and have to accomplish a task for some Jenkins configuration. Please, help me with xml parsing. Just in order to simplify the problem(originally it's a huge Jenkins config.xml file), let's take:
我是Groovy新手。我要完成一项Jenkins配置的任务。请教我解析xml。为了简述问题,下面只是截取了一部分Jenkins的配置文件config.xml:
def input = '''
<shopping>
<category>
<item>Pen</item>
<color>Red</color>
</category>
<category>
<item>Pencil</item>
<color>Black</color>
</category>
<category>
<item>Paper</item>
<color>White</color>
</category>
</shopping>
'''
The target is to change color for Pen only.
目标只是改变Pen的颜色。
I'm trying:
我尝试:
def root = new XmlParser().parseText(input)def supplies = root.category.find{ it.text() == 'Pen' } supplies.parent().color.value() = 'Changed'
Looks so simple but I'm totally lost :( Appreciate any help.
看起来简单我却被搞得一头雾水了。求救。
Almost there...
几乎要实现了。。。
def root = new XmlParser().parseText(input)
def supplies = root.category.find{ it.item.text() == 'Pen' }
supplies.color[0].value = 'Changed'
The thing to note is that color is a Node List whose first node is a text node
要注意的是color是一个Node列表,而其第一个节点是文本节点
....Or use XmlSlurper
to simplify usage of color[0]
and text()
.
或者使用 XmlSlurper 去简化 color[0] 和 text() 。
def root = new XmlSlurper().parseText(input)
def supplies = root.category.find{ it.item == 'Pen' }
supplies.color = 'Changed'
完整代码一:
import groovy.xml.XmlUtil
def input = '''
<shopping>
<category>
<item>Pen</item>
<color>Red</color>
</category>
<category>
<item>Pencil</item>
<color>Black</color>
</category>
<category>
<item>Paper</item>
<color>White</color>
</category>
</shopping>
'''
def root = new XmlParser().parseText(input)
def supplies = root.category.find{ it.item.text() == 'Pen' }
supplies.color[0].value = 'Changed'
//println root.toString()
println XmlUtil.serialize(root)
完整代码二:
import groovy.xml.XmlUtil
def input = '''
<shopping>
<category>
<item>Pen</item>
<color>Red</color>
</category>
<category>
<item>Pencil</item>
<color>Black</color>
</category>
<category>
<item>Paper</item>
<color>White</color>
</category>
</shopping>
'''
def root = new XmlSlurper().parseText(input)
def supplies = root.category.find{ it.item == 'Pen' }
supplies.color = 'Changed'
//println root.toString()
println XmlUtil.serialize(root)
来自: http://wenda.baba.io/questions/3993279/groovy-update-xml.html