Light reading for XML with Groovy

Intuitive, naturally

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

Sponsored: Designing and building an open ITOA architecture