Groovy.xml.MarkupBuilder disable PrettyPrint

I use groovy.xml.MarkupBuilder to create an XML response, but it produces a very printed result that is not needed in the production process.

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

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

But I don’t need any identification - I just need a simple one-line text :)

+7
xml grails groovy xml-serialization
source share
2 answers

IndentPrinter can take three parameters: a PrintWriter , indent string, and boolean addNewLines . You can get the necessary markup by setting addNewLines to false with an empty indent line, for example:

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

Result:

 <methodResponse><resultStatus><result>result</result><resultCode>resultCode</resultCode><errorString>errorString</errorString><errorStringLoc>errorStringLoc</errorStringLoc></resultStatus></methodResponse> 
+16
source share

Just by looking at JavaDocs, there is an IndentPrinter method where you can set the indent level, although it is not going to put all this in one line for you. Perhaps you can write your own Printer

+3
source share

All Articles