1

I have a XML template and I'd like to be able to add/remove/update attributes to the template dynamically, how can I do it?

Thanks.

1
  • Can you show a sample of the template and what you have tried yet?
    – dmahapatro
    Commented May 3, 2014 at 4:51

1 Answer 1

3

It isn't clear from the heading and the question itself whether you are looking for dynamically modifying an XML or an XML template (they are two different entities) hence summarized both options:

Modifying attributes in an XML

def xml = '''
<cars>
  <car type='sedan'>Honda</car>
  <car type='sedan' category='standard'>Toyota</car>
</cars>
'''

def slurper = new XmlSlurper().parseText(xml)

//Add
slurper.car.find { it.text() == 'Honda' }.@year = '2013'

//Modify
slurper.car.find { it.text() == 'Toyota' }.@type = 'Coupe'

//Delete
slurper.car.find { it.text() == 'Toyota' }.attributes().remove( 'category' )

groovy.xml.XmlUtil.serialize( slurper )

Creating an XML from a template using XmlTemplateEngine

Excerpts taken from XmlTemplateEngine API:

def binding = [firstname:"Jochen", lastname:"Theodorou", 
               nickname:"blackdrag", salutation:"Dear"]
 def engine = new groovy.text.XmlTemplateEngine()
 def text = '''<?xml version="1.0" encoding="UTF-8"?>
 <document xmlns:gsp='http://groovy.codehaus.org/2005/gsp' 
           xmlns:foo='baz' type='letter'>
   <gsp:scriptlet>def greeting = "${salutation}est"</gsp:scriptlet>
   <gsp:expression>greeting</gsp:expression>
   <foo:to>$firstname "$nickname" $lastname</foo:to>
   How are you today?
 </document>
 '''
 def template = engine.createTemplate(text).make(binding)
 println template.toString()

Creating XML from a template using MarkupTemplateEngine

Since Groovy 2.3, we can also use MarkupTemplateEngine to create xml in a DSL builder style:

import groovy.text.markup.*
import groovy.text.Template

def xmlTemplate = '''
xmlDeclaration()
cars {
   cars.each {
       car(make: it.make, model: it.model)
   }
}
'''
class Car {
    String make, model
}
def model = [
    cars: [
        new Car(make: 'Peugeot', model: '508'), 
        new Car(make: 'Toyota', model: 'Prius')
    ]
]

def render(xmlTemplate, model) {
    MarkupTemplateEngine engine = 
        new MarkupTemplateEngine(
           new TemplateConfiguration( autoNewLine: true, autoIndent: true ) )
    Template template = engine.createTemplate( xmlTemplate )
    Writable output = template.make( model )
    def writer = new StringWriter()
    output.writeTo( writer )
    println writer
}

render( xmlTemplate, model )
1
  • You gave me more than I want, thank you @dmahapatro. Commented May 4, 2014 at 0:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.