user542103 user542103 - 4 months ago 22
Groovy Question

Grails/Groovy - Render/direct object to XML for saving to file

I'm familiar with using the "render myObject as grails.converters.XML" and with saving a stream/string to a flat file within the "temp" folder of the user's temp/session folder... I'd like to be able to take an object and save it as marshalled xml (in the same way the "render myObject as XML" marshalls it) as a flat .xml file in the users temp folder. IOW, I want to do something like "render myObject as grails.converters.XML to a flat .xml file". Can someone point me in the right direction on how to do this?


You can try groovy.xml.MarkupBuilder if you're handling groovy beans (POGO). If you need to manipulate different kinds of objects, I suggest using XStream.

Its a simple and fast API with low memory footprint. Very useful for marshalling.

For instance, this is an XML doc printed from 2 beans (Person and Address):

def xstream = new XStream()
def joe = new Person(
              new Address(
                'White house',

def xmlDoc = xstream.toXML(joe)

will render:


Then, just use a fileWriter with your xmlDoc for saving to disk or whatever..