Light reading for XML with Groovy

Intuitive, naturally

  • alert
  • submit to reddit

Secure remote control for conventional and virtual desktops

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:

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:

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

Boost IT visibility and business value

More from The Register

next story
'Stop dissing Google or quit': OK, I quit, says Code Club co-founder
And now a message from our sponsors: 'STFU or else'
Why has the web gone to hell? Market chaos and HUMAN NATURE
Tim Berners-Lee isn't happy, but we should be
Microsoft boots 1,500 dodgy apps from the Windows Store
DEVELOPERS! DEVELOPERS! DEVELOPERS! Naughty, misleading developers!
Apple promises to lift Curse of the Drained iPhone 5 Battery
Have you tried turning it off and...? Never mind, here's a replacement
Mozilla's 'Tiles' ads debut in new Firefox nightlies
You can try turning them off and on again
Linux turns 23 and Linus Torvalds celebrates as only he can
No, not with swearing, but by controlling the release cycle
Scratched PC-dispatch patch patched, hatched in batch rematch
Windows security update fixed after triggering blue screens (and screams) of death
This is how I set about making a fortune with my own startup
Would you leave your well-paid job to chase your dream?
prev story


Top 10 endpoint backup mistakes
Avoid the ten endpoint backup mistakes to ensure that your critical corporate data is protected and end user productivity is improved.
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.
Backing up distributed data
Eliminating the redundant use of bandwidth and storage capacity and application consolidation in the modern data center.
The essential guide to IT transformation
ServiceNow discusses three IT transformations that can help CIOs automate IT services to transform IT and the enterprise
Next gen security for virtualised datacentres
Legacy security solutions are inefficient due to the architectural differences between physical and virtual environments.