I need to add @ attribute to the root element of XML fragment in Groovy. I want to use XmlSlurper
. How to do it? Adding elements is easy.
Run this in the Groovy console to verify that it works
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
adding an attribute is the same as reading it:
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
will give you:
<thing stuff='new'><more></more></thing>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With