Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy.xml.MarkupBuilder disable PrettyPrint

I'm using groovy.xml.MarkupBuilder to create XML response but it creates prettyprinted result which is unneeded in production.

        def writer = new StringWriter()
        def xml = new MarkupBuilder(writer)
        def cities = cityApiService.list(params)

        xml.methodResponse() {
            resultStatus() {
                result(cities.result)
                resultCode(cities.resultCode)
                errorString(cities.errorString)
                errorStringLoc(cities.errorStringLoc)
            }
}

This code produces:

<methodResponse> 
  <resultStatus> 
    <result>ok</result> 
    <resultCode>0</resultCode> 
    <errorString></errorString> 
    <errorStringLoc></errorStringLoc> 
  </resultStatus> 
</methodResponse> 

But i don't need any identation - i just want a plain one-row text :)

like image 404
Oleksandr Avatar asked Jul 16 '10 14:07

Oleksandr


2 Answers

IndentPrinter can take three parameters: a PrintWriter, an indent string, and a boolean addNewLines. You can get the markup you want by setting addNewLines to false with an empty indent string, like so:

import groovy.xml.MarkupBuilder

def writer = new StringWriter()
def xml = new MarkupBuilder(new IndentPrinter(new PrintWriter(writer), "", false))

xml.methodResponse() {
    resultStatus() {
        result("result")
        resultCode("resultCode")
        errorString("errorString")
        errorStringLoc("errorStringLoc")
    }
}

println writer.toString()

The result:

<methodResponse><resultStatus><result>result</result><resultCode>resultCode</resultCode><errorString>errorString</errorString><errorStringLoc>errorStringLoc</errorStringLoc></resultStatus></methodResponse>
like image 130
ataylor Avatar answered Sep 18 '22 18:09

ataylor


Just looking at the JavaDocs there is a method on IndentPrinter where you can set the Indent level, although it's not going to put it all on a single line for you. Perhaps you can write your own Printer

like image 28
Goibniu Avatar answered Sep 18 '22 18:09

Goibniu