I just had the occasion to play with Groovy Templates to produce XML.
First I played with the actual groovy.text.XmlTemplateEngine, thusly:
import groovy.text.XmlTemplateEngine
class Thing {
int id
String comment
}
final engine = new XmlTemplateEngine()
final thingTemplateEngine = engine.createTemplate('''<thing id='$id'>$comment</thing>''')
def sb = new StringBuilder()
sb << '<things>' << 'n'
[new Thing(id: 0, comment: 'Hello, XML Template!'),
new Thing(id: 1, comment: 'This is another Thing')].each {
sb << thingTemplateEngine.make([id: it.id, comment: "${it.comment}"]).toString()
}
sb << '</things>'
println sb
This produces:
<things> <thing id='0'> Hello, XML Template! </thing> <thing id='1'> This is another Thing </thing> </things>
Note that XmlTemplateEngine can actually do validation during construction, so if (unlike with this example) you have a schema/DTD defined, you can ensure that what you generate is valid XML. For some applications, this can be quite important.
This is not too shabby, but still a bit messy and ‘bitty’: creating a <thing> is simple, but creating the <things> root element and adding the <thing> children feels like a hack to me (there seems little benefit over plain string concatenation, IMHO) and seems to prevent the possibility of checking against a schema/DTD for the resulting document as a whole.
Groovy offers a second template engine, the groovy.text.SimpleTemplateEngine, viz:
import groovy.text.SimpleTemplateEngine
class Thing {
int id
String comment
}
final thingsTemplate = '''<things>
<% things.each{ thing ->
out << """ <thing id='$thing.id'>$thing.comment</thing>
"""
}%></things>'''
final engine = new SimpleTemplateEngine()
final thingsTemplateEngine = engine.createTemplate(thingsTemplate)
println thingsTemplateEngine.make(things: [new Thing(id: 0, comment: 'Hello, XML Template!'),
new Thing(id: 1, comment: 'This is another Thing')]).toString()
This is a much more general-purpose tool and supports an embedded GSP-style expression syntax that can help make the task at hand cleaner.
The result is essentially the same:
<things> <thing id='0'>Hello, XML Template!</thing> <thing id='1'>This is another Thing</thing> </things>
Note that SimpleTemplateEngine knows nothing about XML so (as far as the generation of valid XML goes) caveat emptor applies.
There is a third template engine, but I’m not going to talk about GStringTemplateEngine here.
Be sure to keep in mind that these engines are text-processing tools: I am hacking XML here, but they have much wider applicability.
