XML Declaration with Groovy markup builders

Groovy builders are great for consuming and creating formats like JSON and XML.  However, I could not easily find an example how to write out an XML document with the XML declaration using the MarkupBuilder.  To do this, you need to use the StreaingMarkupBuilder instead.  Here’s an example that returns the last 10 transactions as XML from a Grails controller:

   1: def index = {

   2:     def xml = new groovy.xml.StreamingMarkupBuilder()

   3:     xml.encoding = "UTF-8"

   4:     render xml.bind {

   5:         mkp.xmlDeclaration()

   6:         Transactions {

   7:             Transaction.findAllByDate(new Date(), [max: 10, sort: "date", order: "desc").each {

   8:                 Transaction {

   9:                     ID(it.id)

  10:                     Date(it.date)

  11:                     Total(it.total)

  12:                 } 

  13:             }

  14:         }    

  15:     }.toString()

  16: }

 

With this, you will get a nice well formed XML document:

   1: <?xml version="1.0"?>

   2: <Transactions>

   3:     <Transaction>

   4:         <ID>193710</TD>

   5:         <Date>2009-10-18 17:09:24</Date>

   6:         <Total>123.12</Total>

   7:     </Transaction>

   8:     ...

   9: </Transactions>