Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to pretty print XML response in grails

Given this in a grails action:

def xml = {
    rss(version: '2.0') {
        ...
    }
}
render(contentType: 'application/rss+xml', xml)

I see this:

<rss><channel><title></title><description></description><link></link><item></item></channel></rss>

Is there an easy way to pretty print the XML? Something built into the render method, perhaps?

like image 879
danb Avatar asked Oct 23 '08 21:10

danb


3 Answers

Use XmlUtil :

def xml = "<rss><channel><title></title><description>" +
   "</description><link></link><item></item></channel></rss>"

println XmlUtil.serialize(xml)
like image 80
Fabien Barbier Avatar answered Oct 01 '22 22:10

Fabien Barbier


This is a simple way to pretty-print XML, using Groovy code only:

def xml = "<rss><channel><title></title><description>" +
   "</description><link></link><item></item></channel></rss>"

def stringWriter = new StringWriter()
def node = new XmlParser().parseText(xml);
new XmlNodePrinter(new PrintWriter(stringWriter)).print(node)

println stringWriter.toString()

results in:

<rss>
  <channel>
    <title/>
    <description/>
    <link/>
    <item/>
  </channel>
</rss>
like image 36
seansand Avatar answered Oct 01 '22 22:10

seansand


According to the reference docs, you can use the following configuration option to enable pretty printing:

 grails.converters.default.pretty.print (Boolean)
 //Whether the default output of the Converters is pretty-printed ( default: false )
like image 22
Eric Levine Avatar answered Oct 01 '22 23:10

Eric Levine