我需要在 Groovy 中将 @ 属性添加到 XML 片段的根元素。我想使用 XmlSlurper
。怎么做?添加元素很容易。
最佳答案
在 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
关于groovy - 如何使用 Groovy 添加 XML 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7795494/