Feeds

Groovy: XML without the bloat

Flexible strings

Next gen security for virtualised datacentres

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.®

Secure remote control for conventional and virtual desktops

More from The Register

next story
Why has the web gone to hell? Market chaos and HUMAN NATURE
Tim Berners-Lee isn't happy, but we should be
Mozilla's 'Tiles' ads debut in new Firefox nightlies
You can try turning them off and on again
Microsoft boots 1,500 dodgy apps from the Windows Store
DEVELOPERS! DEVELOPERS! DEVELOPERS! Naughty, misleading developers!
'Stop dissing Google or quit': OK, I quit, says Code Club co-founder
And now a message from our sponsors: 'STFU or else'
Apple promises to lift Curse of the Drained iPhone 5 Battery
Have you tried turning it off and...? Never mind, here's a replacement
Uber, Lyft and cutting corners: The true face of the Sharing Economy
Casual labour and tired ideas = not really web-tastic
Linux turns 23 and Linus Torvalds celebrates as only he can
No, not with swearing, but by controlling the release cycle
prev story

Whitepapers

Gartner critical capabilities for enterprise endpoint backup
Learn why inSync received the highest overall rating from Druva and is the top choice for the mobile workforce.
Implementing global e-invoicing with guaranteed legal certainty
Explaining the role local tax compliance plays in successful supply chain management and e-business and how leading global brands are addressing this.
Rethinking backup and recovery in the modern data center
Combining intelligence, operational analytics, and automation to enable efficient, data-driven IT organizations using the HP ABR approach.
Consolidation: The Foundation for IT Business Transformation
In this whitepaper learn how effective consolidation of IT and business resources can enable multiple, meaningful business benefits.
Next gen security for virtualised datacentres
Legacy security solutions are inefficient due to the architectural differences between physical and virtual environments.