Pregunta

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.

¿Fue útil?

Solución

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 )
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top