user542103 user542103 - 3 months ago 15
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?

Answer

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(
             'Joe',
             'Biden',
              new Address(
                'White house',
                '222',
                'Whashington',
                'US'
              )
            )

def xmlDoc = xstream.toXML(joe)

will render:

<Person>
  <name>Joe</name>
  <lastName>Biden</lastName>
  <Address>
    <street>Whitehouse</street>
    <postcode>222</postcode>
    <city>Washington</city>
    <country>US</country>
  </Address>
</Person>

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