我正在使用 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>
关于xml - groovy.xml.MarkupBuilder 禁用 PrettyPrint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3266115/