我正在使用groovy.xml.MarkupBuilder创建XML响应,但是它会创建 pretty-print 结果,这在生产中是不需要的。

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

此代码产生:
<methodResponse>
  <resultStatus>
    <result>ok</result>
    <resultCode>0</resultCode>
    <errorString></errorString>
    <errorStringLoc></errorStringLoc>
  </resultStatus>
</methodResponse>

但是我不需要任何标识-我只想要一个简单的单行文本:)

最佳答案

IndentPrinter 可以采用三个参数:PrintWriter,缩进字符串和 bool addNewLines。您可以通过使用空的缩进字符串将addNewLines设置为false来获得所需的标记,如下所示:

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

结果:
<methodResponse><resultStatus><result>result</result><resultCode>resultCode</resultCode><errorString>errorString</errorString><errorStringLoc>errorStringLoc</errorStringLoc></resultStatus></methodResponse>

10-07 23:08