Feeds

Groovy: XML without the bloat

Flexible strings

Beginner's guide to SSL certificates

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

Choosing a cloud hosting partner with confidence

More from The Register

next story
Be real, Apple: In-app goodie grab games AREN'T FREE – EU
Cupertino stands down after Euro legal threats
Download alert: Nearly ALL top 100 Android, iOS paid apps hacked
Attack of the Clones? Yeah, but much, much scarier – report
You stupid BRICK! PCs running Avast AV can't handle Windows fixes
Fix issued, fingers pointed, forums in flames
Microsoft: Your Linux Docker containers are now OURS to command
New tool lets admins wrangle Linux apps from Windows
Facebook, working on Facebook at Work, works on Facebook. At Work
You don't want your cat or drunk pics at the office
Soz, web devs: Google snatches its Wallet off the table
Killing off web service in 3 months... but app-happy bonkers are fine
First in line to order a Nexus 6? AT&T has a BRICK for you
Black Screen of Death plagues early Google-mobe batch
prev story

Whitepapers

Choosing cloud Backup services
Demystify how you can address your data protection needs in your small- to medium-sized business and select the best online backup service to meet your needs.
A strategic approach to identity relationship management
ForgeRock commissioned Forrester to evaluate companies’ IAM practices and requirements when it comes to customer-facing scenarios versus employee-facing ones.
How to determine if cloud backup is right for your servers
Two key factors, technical feasibility and TCO economics, that backup and IT operations managers should consider when assessing cloud backup.
Reg Reader Research: SaaS based Email and Office Productivity Tools
Read this Reg reader report which provides advice and guidance for SMBs towards the use of SaaS based email and Office productivity tools.
The Heartbleed Bug: how to protect your business with Symantec
What happens when the next Heartbleed (or worse) comes along, and what can you do to weather another chapter in an all-too-familiar string of debilitating attacks?