簡體   English   中英

groovy.xml.MarkupBuilder禁用PrettyPrint

[英]groovy.xml.MarkupBuilder disable PrettyPrint

我正在使用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 ,縮進字符串和boolean 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>

僅查看JavaDocs,就可以在IndentPrinter上設置一個方法來設置Indent級別,盡管這不會將所有內容放在一行中。 也許您可以編寫自己的Printer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM