Feeds

Light reading for XML with Groovy

Intuitive, naturally

  • alert
  • submit to reddit

Build a business case: developing custom apps

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

Boost IT visibility and business value

More from The Register

next story
KDE releases ice-cream coloured Plasma 5 just in time for summer
Melty but refreshing - popular rival to Mint's Cinnamon's still a work in progress
Leaked Windows Phone 8.1 Update specs tease details of Nokia's next mobes
New screen sizes, dual SIMs, voice over LTE, and more
Mozilla keeps its Beard, hopes anti-gay marriage troubles are now over
Plenty on new CEO's todo list – starting with Firefox's slipping grasp
Apple: We'll unleash OS X Yosemite beta on the MASSES on 24 July
Starting today, regular fanbois will be guinea pigs, it tells Reg
PEAK LANDFILL: Why tablet gloom is good news for Windows users
Sinofsky's hybrid strategy looks dafter than ever
Another day, another Firefox: Version 31 is upon us ALREADY
Web devs, Mozilla really wants you to like this one
Secure microkernel that uses maths to be 'bug free' goes open source
Hacker-repelling, drone-protecting code will soon be yours to tweak as you see fit
prev story

Whitepapers

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.
Boost IT visibility and business value
How building a great service catalog relieves pressure points and demonstrates the value of IT service management.
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.
The Essential Guide to IT Transformation
ServiceNow discusses three IT transformations that can help CIO's automate IT services to transform IT and the enterprise.
Maximize storage efficiency across the enterprise
The HP StoreOnce backup solution offers highly flexible, centrally managed, and highly efficient data protection for any enterprise.