Groovy Grails REST service helper
August 23rd, 2008h4. Quick Tip on Markup Builder example is from a Domain object (Book) that contains enum’s if you have only simple datatypes then “render as XML” works just fine
String toXML() {
StringWriter buffer = new StringWriter()
def xml = new MarkupBuilder(buffer)
xml.book() {
id(this.id)
author(this.authorName)
pagecount(pagecount:this.pagecount)
}
return buffer.toString() + “\\n”
}
Keep in mind that the difference between author and pagecount looks like this in the xml
222
Toddecus
You can see that the pagecount is much more terse but may present challenges on parsing.h4. Quick Tip on parsing say a Rest service that returns the XML above: This assumes you used an XMLSlurper to parse the text into a GPathResult
{code}
static Book fromXML(GPathResult bookXML)
{
def book = new Book()
book.id = Integer.parseInt(bookXML.id.text())
book.author = bookXML.author.text()
book.pagecount = Integer.parseInt(bookXML.pagecount.@pagecount.text())
return book
}
{code}Pay special attention to the use of the “at” symbol to get access to the property on the field as opposed to the field contents.
h4. If you really cared about terse XML in your REST service you might even do this:
{code}
String toXML() {
StringWriter buffer = new StringWriter()
def xml = new MarkupBuilder(buffer)
xml.book(id: this.id, author:this.authorName, pagecount:this.pagecount){}
return buffer.toString() + “\\n”
}
{code}
Which would result in XML like this:
{code}
{code}
doesn’t help much if your domain object contains a set of sub elements though ![]()