尝试用:
def str = '''<TargetValue>4</TargetValue>
<TargetValue></TargetValue>
<TargetValue>2</TargetValue>
'''
str.replaceAll(/[0-9]+/) {
Math.abs(new Random().nextInt() % 10) + 1
}
UPDATE
然后尝试类似:
def str = '''<TargetValue>4</TargetValue>
<TargetValue></TargetValue>
<TargetValue>2</TargetValue>
'''
str.replaceAll(/\<TargetValue\>\d+\<\/TargetValue\>/) {
'<TargetValue>' + (Math.abs(new Random().nextInt() % 10) + 1) + '</TargetValue>'
}
更新2
由于@tim_yates建议,最好使用XmlSlurper
比正则表达式,但你需要一个良好的XML解析,所以在你的例子你的XML需要一个根节点得到很好的形成。
def str = '''<root>
<TargetValue>4</TargetValue>
<TargetValue></TargetValue>
<TargetValue>2</TargetValue>
</root>
'''
def xml = new XmlSlurper().parseText(str)
xml.'**'.findAll {
it.name() == 'TargetValue'
}.each {
it.replaceBody(Math.abs(new Random().nextInt() % 10) + 1)
}
println XmlUtil.serialize(xml)
这个脚本日志:然后,你可以为你使用正则表达式使用XmlSlurper
做同样的
<?xml version="1.0" encoding="UTF-8"?>
<root>
<TargetValue>8</TargetValue>
<TargetValue>3</TargetValue>
<TargetValue>6</TargetValue>
</root>
希望它能帮助,
shoul You不要用正则表达式解析XML。看看XmlSlurper或XmlParser –