Best way to pretty print XML response in grails
Asked Answered
Q

4

11

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?

Quiescent answered 23/10, 2008 at 21:50 Comment(0)
O
4

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 )
Openhearth answered 11/8, 2010 at 15:19 Comment(0)
S
19

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>
Sulphuryl answered 24/10, 2008 at 0:33 Comment(1)
this does however seem to add whitespace within tags that shouldn't have. There are a couple of notes about this here: jira.codehaus.org/browse/GROOVY-3265Busey
O
4

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 )
Openhearth answered 11/8, 2010 at 15:19 Comment(0)
M
3

Use MarkupBuilder to pretty-print your Groovy xml

def writer = new StringWriter()
def xml = new MarkupBuilder (writer)

xml.rss(version: '2.0') {
        ...
    }
}

render(contentType: 'application/rss+xml', writer.toString())
Monophyletic answered 13/6, 2011 at 5:2 Comment(0)
C
3

Use XmlUtil :

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

println XmlUtil.serialize(xml)
Chloromycetin answered 29/2, 2012 at 22:8 Comment(1)
for me (groovy 1.8 / windows machine) this is printing without any indentation (so not pretty).Penzance

© 2022 - 2024 — McMap. All rights reserved.