我需要在Groovy中将@属性添加到XML片段的根元素中。我想使用XmlSlurper
。怎么做?添加元素很容易。
答案 0 :(得分:12)
在Groovy控制台中运行它以验证它是否正常工作
import groovy.xml.StreamingMarkupBuilder
// the original XML
def input = "<foo><bar></bar></foo>"
// add attributeName="attributeValue" to the root
def root = new XmlSlurper().parseText(input)
root.@attributeName = 'attributeValue'
// get the modified XML and check that it worked
def outputBuilder = new StreamingMarkupBuilder()
String updatedXml = outputBuilder.bind{ mkp.yield root }
assert "<foo attributeName='attributeValue'><bar></bar></foo>" == updatedXml
答案 1 :(得分:1)
添加属性与读取属性相同:
import groovy.xml.StreamingMarkupBuilder
def input = '''
<thing>
<more>
</more>
</thing>'''
def root = new XmlSlurper().parseText(input)
root.@stuff = 'new'
def outputBuilder = new StreamingMarkupBuilder()
String result = outputBuilder.bind{ mkp.yield root }
println result
会给你:
<thing stuff='new'><more></more></thing>