groovy.xml.MarkupBuilder禁用PrettyPrint

时间:2010-07-16 14:54:40

标签: xml grails groovy xml-serialization

我正在使用groovy.xml.MarkupBuilder来创建XML响应,但它会创建在生产中不需要的漂亮打印结果。

        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> 

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

2 个答案:

答案 0 :(得分:17)

IndentPrinter可以使用三个参数:PrintWriter,缩进字符串和布尔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>

答案 1 :(得分:3)

只需查看JavaDocs,就可以在IndentPrinter上设置一个方法来设置缩进级别,尽管它不会将所有内容全部放在一行上。也许你可以自己编写Printer

相关问题