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!
One thing you could do (in your controller) is to send the XML back from the render method like so:
def callxml = {
def call = Call.get( params.id )
render( contentType:"text/xml" ) {
vxml( version:'2.1' ) {
var( name:'hi', expr:call.message )
}
}
}
Or, you could add a method to the Call class, so it knows how to convert itself to XML as a String:
class Call {
String message
String toXml() {
def writer = new StringWriter()
new groovy.xml.MarkupBuilder( writer ).with { xml ->
xml.doubleQuotes = true
vxml(version:'2.1'){
var(name:"hi", expr:"${this.message}")
}
}
writer.toString()
}
}
Then you should be able to call call.toXml()
精彩评论