Tuesday, August 17, 2010

Grails: using Groovy MarkupBuilder to render properly indented XML

When using Grails, the easiest way to render XML is to use 
 render obj as XML
command. However, that returns the entire XML on one line.

If you want XML to look pretty, you can use groovy.xml.MarkupBuilder

def showXml = {
    def writer = new StringWriter() 
    new MarkupBuilder(writer).root {
        child1 {
            child2('someValue')
        }       
    }

    render(text: writer.toString(), contentType: "text/xml")
}

This will produce a neat output where each tag is on a new line and properly indented.

No comments:

Post a Comment