Feeds

Light reading for XML with Groovy

Intuitive, naturally

  • alert
  • submit to reddit

Top 5 reasons to deploy VMware with Tegile

If we're really interested in walking the tree then there are a couple of methods explicitly designed to do all the work for us, and we get a choice of how we want to order our walk, depth first or breadth first. Let's take a look at them both:

println '\nDepth first...'
pers.depthFirst().each {println it.name()}
println '\nBreadth first....'
pers.breadthFirst().each {println it.name()} 

Both of these will walk the XML tree encoded in our XmlSlurper object and print out the element names. Here's a bit of quick and dirty script to print out the attributes of every element that has them:


pers.depthFirst().each {   
atts = it.attributes().size() > 0 ? it.name() + " = " + 
        it.attributes() : null
                if (atts) println atts
}

Running against our sample file that produces the following output:


person = ["first_name":"john", "surname":"smith"]
kids = ["count":"2"]
person = ["first_name":"jill", "surname":"jones"]
kids = ["count":"0"]
person = ["first_name":"clark", "surname":"kent"]
kids = ["count":"3"]

Another advantage of XmlSlurper is that we can address elements directly by name. In our case if we're crafting code that's specifically designed to process pers.xml documents, why not use the people, person, age, gender and kids elements directly in our code?

Here's how we can access the age of every person in the document:

pers.person.age.each { println it}

We can make some adjustments to the data too. Say we want to up the age of the second person in the file:


pers.person.age[1]='999'
println pers.person.getAt(1).age

Note how we used an index method getAt() to grab the updated value at the end there.

We can do more than simply read and write values. Let's say we want to sum the ages of all the people in our XML file. We can iterate over the age elements, convert to integers and perform a running sum:


sum_of_ages=0
pers.person.age.each {sum_of_ages+=it.toInteger() }
println 'sum = ' + sum_of_ages

Before we finish off, we ought to take a look at how we do some processing that's a bit more demanding than the relatively straightforward accessing of elements and attributes that we've managed so far.

XmlSlurper includes both a find and a findAll method, which makes for straightforward processing of XML data based on content. While in no way a replacement for XPath, for simple cases it provides a good way to filter nodes.

For example, let's say we want to extract those person nodes that don't have any kids. That means looking at the count attribute for the kids elements and only accessing those nodes that have a value greater than zero. With Groovy we can do it as follows:


def with_kids=pers.person.findAll {it.kids.@count.toInteger() > 0}

First we use the findAll method on the person elements, then inside the closure we access the count attribute of the kids element, convert to an integer and then test for a value greater than zero. The result of this is assigned to the with_kids object, which we can process further:


println "Number of people with kids: " + with_kids.size()
with_kids.each {println it.@first_name.text() + " has " +
it.kids.@count.toInteger() + " kids"}

This produces the following output:


Number of people with kids: 2
john has 2 kids
clark has 3 kids

As you can see, then, the XmlSlurper class provides a full set of methods for processing XML data. While it doesn't take the place of a complete framework, or provide all of the functionality of XPath, XmlSlurper does provide convenience methods aplenty. For many common XML processing activities it works, is easy to understand and follow, and avoids the verbosity required for performing similar activities in pure Java code.®

Choosing a cloud hosting partner with confidence

More from The Register

next story
UNIX greybeards threaten Debian fork over systemd plan
'Veteran Unix Admins' fear desktop emphasis is betraying open source
Netscape Navigator - the browser that started it all - turns 20
It was 20 years ago today, Marc Andreeesen taught the band to play
Redmond top man Satya Nadella: 'Microsoft LOVES Linux'
Open-source 'love' fairly runneth over at cloud event
Google+ goes TITSUP. But WHO knew? How long? Anyone ... Hello ...
Wobbly Gmail, Contacts, Calendar on the other hand ...
Chrome 38's new HTML tag support makes fatties FIT and SKINNIER
First browser to protect networks' bandwith using official spec
Admins! Never mind POODLE, there're NEW OpenSSL bugs to splat
Four new patches for open-source crypto libraries
Torvalds CONFESSES: 'I'm pretty good at alienating devs'
Admits to 'a metric ****load' of mistakes during work with Linux collaborators
prev story

Whitepapers

Forging a new future with identity relationship management
Learn about ForgeRock's next generation IRM platform and how it is designed to empower CEOS's and enterprises to engage with consumers.
Why and how to choose the right cloud vendor
The benefits of cloud-based storage in your processes. Eliminate onsite, disk-based backup and archiving in favor of cloud-based data protection.
Three 1TB solid state scorchers up for grabs
Big SSDs can be expensive but think big and think free because you could be the lucky winner of one of three 1TB Samsung SSD 840 EVO drives that we’re giving away worth over £300 apiece.
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.
Security for virtualized datacentres
Legacy security solutions are inefficient due to the architectural differences between physical and virtual environments.