加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

groovy.xml.MarkupBuilder禁用PrettyPrint

发布时间:2020-12-14 16:32:40 所属栏目:大数据 来源:网络整理
导读:我正在使用groovy.xml.MarkupBuilder来创建 XML响应,但它创建了生成中不需要的漂亮打印结果. def writer = new StringWriter() def xml = new MarkupBuilder(writer) def cities = cityApiService.list(params) xml.methodResponse() { resultStatus() { res
我正在使用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>

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

解决方法

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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读