我正在尝试将XML转换器创建的XML片段注入MarkupBuilder。
但是我无法正确地进行格式化,似乎有不必要的中间序列化步骤。
import grails.converters.XML
import groovy.xml.MarkupBuilder
//...
def writer = new StringWriter ()
def xml = new MarkupBuilder (writer)
xml.response {
status ("OK")
myList.each { it as XML } //Insert objects by converting to XML
}
println writer.toString()
所需的输出是
<response>
<status>OK</status>
<foo>
<field>5</field>
</foo>
<foo>
<field>5</field>
</foo>
</response>
我目前的尝试是
def writer = new StringWriter ()
def xml = new MarkupBuilder (writer)
xml.response {
status ("OK")
myList.each {
xml.mkp.yieldUnescaped ( it as XML )
}
}
println writer.toString()
但是目前每个xml片段都以
开头 <?xml version="1.0" encoding="UTF-8"?>
有没有更好的方法来实现这个目标?
答案 0 :(得分:2)
更流畅的方法是将writer
直接传递给render
类的XML
方法,如下所示。
def writer = new StringWriter ()
def xml = new MarkupBuilder (writer)
xml.response {
status ("OK")
def xmlist = myList as XML
xmlist.render(writer)
}
您仍然会有一次编码信息,因为render
只是将其写入传入的任何writer
。
我看到2个选项可以摆脱这种编码信息:
xml.response {
status ("OK")
def xmlist = myList as XML
xml.mkp.yieldUnescaped (xmlist.toString() - "<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
}