Best way to pretty print XML response in grails

▼魔方 西西 提交于 2019-11-28 23:38:45

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 )

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>

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())

Use XmlUtil :

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

println XmlUtil.serialize(xml)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!