Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add XML attribute using Groovy?

Tags:

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.

like image 911
Lukasz Avatar asked Dec 09 '22 05:12

Lukasz


2 Answers

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
like image 70
Dónal Avatar answered Apr 10 '23 19:04

Dónal


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>
like image 41
codelark Avatar answered Apr 10 '23 17:04

codelark