首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >groovy.xml.MarkupBuilder禁用PrettyPrint

groovy.xml.MarkupBuilder禁用PrettyPrint
EN

Stack Overflow用户
提问于 2010-07-16 22:54:40
回答 2查看 2.9K关注 0票数 7

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

代码语言:javascript
复制
        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)
            }
}

这段代码产生:

代码语言:javascript
复制
<methodResponse> 
  <resultStatus> 
    <result>ok</result> 
    <resultCode>0</resultCode> 
    <errorString></errorString> 
    <errorStringLoc></errorStringLoc> 
  </resultStatus> 
</methodResponse> 

但我不需要任何标识-我只需要一个纯单行文本:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-07-17 00:00:35

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

代码语言:javascript
复制
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()

结果是:

代码语言:javascript
复制
<methodResponse><resultStatus><result>result</result><resultCode>resultCode</resultCode><errorString>errorString</errorString><errorStringLoc>errorStringLoc</errorStringLoc></resultStatus></methodResponse>
票数 17
EN

Stack Overflow用户

发布于 2010-07-16 23:19:17

看看JavaDocs,在IndentPrinter上有一个方法可以设置缩进级别,尽管它不会把所有的缩进级别都放在一行中。也许您可以编写自己的Printer

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3266115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档