Groovy: XML without the bloat

Flexible strings

Groovy also includes a very handy feature for handling tree structures: builders. In the same way that Groovy has excellent built-in support for collections - lists and maps - it also comes with support for trees. Builders are perfect for all kinds of tree structures, from HTML to GUI elements to XML.

For a real-world example let’s say we have a nested structure that we want to export to XML. It could be the results of a query to a MySQL database, the data from a class hierarchy or some other source. In our example the data relates to a simple personnel database, with a record for each person. We store this as follows:

pers=["john":[surname:"smith",age:37,gender:'m',children:2],
      "jill":[surname:"jones",age:28,gender:'f',children:0]
      ]

Before we dive into the builder, let’s remind ourselves of what we can do with Groovy’s iterators and closures:

pers.each {name, data ->
  println name + ' ' + data['surname'] + ' is ' + data['age'] + ' years old'
}

That single line of code iterates through each person’s record, mapping the key value to the name variable, and the map of data to the variable we’ve cleverly labeled data. We can then address the contents of the data map directly by name. Running that line of code gives the following on the command line:

john smith is 37 years old
jill jones is 28 years old

We’re going to do something similar using a groovy.xml.MarkupBuilder object, as shown below:

s_xml=new StringWriter()
builder=new groovy.xml.MarkupBuilder(s_xml)
people=builder.people{
  pers.each{ name, data ->
    person(first_name:name, surname:data['surname']){
      age(data['age']){}
      gender(data['gender']){}
      children('count':data['children']){}
    }
  }
}

println s_xml

This clever little bit of code creates a builder object that writes its data to the StringWriter variable called s_xml. The builder uses a closure that contains our data source called pers, which uses the "each" iterator as in the previous example. The magic is in the pers.each closure. Here we use a set of pseudo-methods called person, age, gender and children. These are all turned into XML elements, and the arguments to these pseudo-methods are the values of the elements. If we run the above code we can see the results clearly enough:

<people>
  <person first_name='john' surname='smith'>
    <age>37</age>
    <gender>m</gender>
    <children count='2' />
  </person>
  <person first_name='jill' surname='jones'>
    <age>28</age>
    <gender>f</gender>
    <children count='0' />
  </person>
</people>

No wonder the language is called Groovy! We can even spool that out to file in a few lines of code as well:

str=s_xml.toString()
def fw= new FileWriter('pers.xml')
'<?xml version="1.0"?>\n'.each{fw.write(it)}
s_xml.toString().each{fw.write(it)}
fw.close()

Anyone who’s ever had to write code to get complex, hierarchical data out into XML will recognize that this is a very easy and natural way to go about navigating through the data and organizing it into the required format.

In second part of this series, I shall turn to the other side of this programming equation - reading in XML and querying or transforming it.®

Sponsored: Network DDoS protection