Best way to pretty print XML response in grails

2019-01-23 16:40发布

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?

4条回答
祖国的老花朵
2楼-- · 2019-01-23 16:48

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 )
查看更多
看我几分像从前
3楼-- · 2019-01-23 16:58

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())
查看更多
SAY GOODBYE
4楼-- · 2019-01-23 17:01

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>
查看更多
Luminary・发光体
5楼-- · 2019-01-23 17:03

Use XmlUtil :

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

println XmlUtil.serialize(xml)
查看更多
登录 后发表回答