views:

39

answers:

2

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

+1  A: 

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

Rulmeq
yep, i saw that - i could disable identation but line breaks are still present.
Olexandr
+1  A: 

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>
ataylor