如何使用Groovy添加XML属性?

Luk*_*asz 4 groovy

我需要在Groovy中将@属性添加到XML片段的根元素中.我想用XmlSlurper.怎么做?添加元素很容易.

Dón*_*nal 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
Run Code Online (Sandbox Code Playgroud)