Lukasz
Lukasz

Reputation: 7662

How to add XML attribute using Groovy?

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.

Upvotes: 5

Views: 9644

Answers (2)

Dónal
Dónal

Reputation: 187529

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

Upvotes: 14

codelark
codelark

Reputation: 12334

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>

Upvotes: 3

Related Questions