Skip Navigation Links

Easy SQL to XML with zero.data and Groovy

Posted by brandon on January 14th, 2009. Other posts by brandon

Groovy can have some sweet sugar syntax.

Consider the XML Builder combined with a database query using the zero.data module:

def data = zero.data.groovy.Manager.create('mydb')
def xml = new groovy.xml.MarkupBuilder(request.writer[])
 
xml.records() {
    data.eachRow('SELECT * FROM person') { row ->
        item(id: row.id, name: row.name)
    }
}
 
request.headers.out.'Content-Type' = 'application/xml'

Drop this script in the public folder, “public/sql2xml.groovy” for instance. Assuming a database is configured in zero.config for “mydb” and there exists a “person” table with at least the “id” and “name” as columns and some data, then this short snippet of code, accessible at http://localhost:8080/sql2xml.groovy” will output the following XML:

<records>
  <item id='1' name='brandon' />
  <item id='2' name='justin' />
</records>

Let’s break down the example:

  1. Get an instance of data API configured to connect to the database in zero.config

    def data = zero.data.groovy.Manager.create('mydb')
  2. Create a new XML builder provided by Groovy and make it output to the HTTP response

    def xml = new groovy.xml.MarkupBuilder(request.writer[])
  3. Start building the XML with as the root XML node

    xml.records() {
  4. Execute the SQL statement using zero.data APIs and loop over each row in the ResultSet; the “row” parameter into the Groovy closure is actually a Map where the key is the column name and the value is the row value from the ResultSet; this ResultSet to Map conversion is provided by the zero.data API

        data.eachRow('SELECT * FROM person') { row ->
  5. Use the Groovy builder syntax to add data from the “row” to the XML output; the syntax on this line says that if “item” method is not found, it becomes a node in the XML output <item id=”idValue” name=”nameValue />

            item(id: row.id, name: row.name)
  6. End the closures

        }
    }

One Response to “Easy SQL to XML with zero.data and Groovy”

  1. Project Zero Blog » Blog Archive » Introducing the WebSphere sMash Cookbook Says:

    [...] Easy SQL to XML with zero.data and Groovy [...]