开发者

groovy.xml.MarkupBuilder disable PrettyPrint

开发者 https://www.devze.com 2023-01-07 06:16 出处:网络
I\'m using groovy.xml.MarkupBuilder to create XML response but it creates prettyprinted result which is unneeded in production.

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() {
开发者_如何学Go                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 :)


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>


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

0

精彩评论

暂无评论...
验证码 换一张
取 消