如何在 Grails 中动态渲染 XML?
我正在设置一个应用程序,该应用程序根据特定于每个呼叫实例的 XML 文件发起电话呼叫。出于测试目的,我使用 Groovy MarkupBuilder 和 StringWriter 方法将 XML 写入单个文件,然后在下次启动调用时覆盖该文件。
但是,这在生产中不起作用,因为我们将覆盖当前正在使用的 XML。因此,我想在控制器中动态创建 XML,方法是使用以下内容调用它:
callInstance.createXml()
使用“createXml”方法,其中包含如何专门为每个调用呈现 XML 的规则。
我发现很多人询问如何将对象转换为动态创建的 XML 文件,但这有点不同,因为我必须使用 MarkupBuilder。
为了快速参考,这里是我正在处理的小例子:
def f1 = new File('filename')
f1.delete()
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.doubleQuotes = true
xml.vxml(version:'2.1'){
property(name:"termchar", value:"#")
var(name:"hi", expr:"'Hello!'")
xml.form(){
block(){
value(expr:"hi")
xml.goto(next:"#next") //etc, etc
}
}
}
//break
f1.createNewFile()
f1 << writer.toString()
提前致谢!
I'm setting up an application that initiates phone calls based on XML files specific to each call instance. For testing purposes, I was using the Groovy MarkupBuilder and StringWriter methods to write my XMLs to a single file, and then overwrite that file the next time a call was initiated.
However, this will not work in production, because we will be overwriting XML that is currently in use. So, I'd like to dynamically create XML in a controller by calling it with something like:
callInstance.createXml()
with the "createXml" method containing the rules for how to render the XML specifically for each call.
I've found multiple instances of people asking how to turn an object into a dynamically created XML file, but this is a little different since I'm having to use the MarkupBuilder.
For a quick reference, here's small example of what I'm working with:
def f1 = new File('filename')
f1.delete()
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.doubleQuotes = true
xml.vxml(version:'2.1'){
property(name:"termchar", value:"#")
var(name:"hi", expr:"'Hello!'")
xml.form(){
block(){
value(expr:"hi")
xml.goto(next:"#next") //etc, etc
}
}
}
//break
f1.createNewFile()
f1 << writer.toString()
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以(在控制器中)做的一件事是 从渲染方法发送回 XML,如下所示:
或者,您可以向 Call 类添加一个方法,这样它就知道如何将自身转换为 XML,如下所示字符串:
那么您应该能够调用
call.toXml()
One thing you could do (in your controller) is to send the XML back from the render method like so:
Or, you could add a method to the Call class, so it knows how to convert itself to XML as a String:
Then you should be able to call
call.toXml()