Transforming Data to XML

We can get the data from the database and create different representations using Groovy builders. Here is an example that creates an XML representation (see Building XML) of the data in the weather table:

WorkingWithDatabases/Weather.groovy
 
bldr = ​new​ groovy.xml.MarkupBuilder()
 
 
bldr.weather {
 
sql.eachRow(​'SELECT * from weather'​) {
 
city(name: it.city, temperature: it.temperature)
 
}
 
}

The code produces this XML output:

WorkingWithDatabases/Weather.output
 
<weather>
 
<city name='Austin' temperature='48' />
 
<city name='Baton Rouge' temperature='57' />
 
<city name='Jackson' temperature='50' />
 
<city name='Montgomery' temperature='53' />
 
<city name='Phoenix' temperature='67' />
 
<city name='Sacramento' ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.