Feeds

Light reading for XML with Groovy

Intuitive, naturally

  • alert
  • submit to reddit

Security for virtualized datacentres

Hands on, part 2 Groovy, unlike Java, provides a relatively streamlined way to read and write XML documents. In the first part of my two-piece tutorial, I looked at how you can use Groovy's flexible strings, closures and iterators to quickly create XML fragments and files.

The emphasis was on making the most of Groovy as a scripting language rather than on making use of the heavyweight XML parsers and libraries that it can access due to its use of the Java Virtual Machine (JVM) and ability to access Java libraries.

This time, I turn to the other side of the equation, and look at how you can use Groovy to quickly and simply process XML.

Groovy can be used with the full range of Java XML parsers and libraries - so in addition to vanilla DOM and SAX, you can use JDOM, XOM, StAX and the whole alphabet soup of alternatives that are available for the Java platform.

What we're interested in here, though, is using Groovy for the kind of ad-hoc scripting tasks that have traditionally been the preserve of languages such as Perl. Instead of the heavyweights we are going to focus on Groovy's XmlSlurper class, which provides a very natural and intuitive interface to XML.

Our example data is the following simple XML file:


<?xml version="1.0"?>
<people>
  <person first_name='john' surname='smith'>
    <age>37</age>
    <gender>m</gender>
    <kids count='2' />
  </person>
  <person first_name='jill' surname='jones'>
    <age>28</age>
    <gender>f</gender>
    <kids count='0' />
  </person>
  <person first_name='clark' surname='kent'>
    <age>22</age>
    <gender>m</gender>
    <kids count='3' />
  </person>  
</people>

The first task is to parse the file - which we've called pers.xml and have placed in a /groovy/progs directory - from disk and make it available for processing. In Groovy this is a one-liner:

def pers=new XmlSlurper().parse(new File("/groovy/progs/pers.xml"))

Once we've got our XmlSlurper object we can use dot notation to access elements and attributes within it. Using dot notation is a very natural way of working for Java developers, and helps to bridge the gap between object notation and hierarchic XML structure. The top-level element in this case is people, but we can find that simply enough:

        println pers.name()

The above code will print people to the command-line or shell. Want to find out what the child elements are? Easy:


pers.children().each { println it.name() }

But why stop there? We can move up and down the tree easily enough. Say we want to find the children of each of the child elements in turn. Again, it's trivial:

pers.children().children().each {println it.name()}

That should print out three lots of age, gender and kids. Getting hold of attributes isn't much more difficult:


pers.children().each {println it.attributes()}

The output of that line of code is:


["first_name":"john", "surname":"smith"]
["first_name":"jill", "surname":"jones"]
["first_name":"clark", "surname":"kent"]

Note that the above is a map, with the attribute names acting as the keys.

Internet Security Threat Report 2014

More from The Register

next story
Microsoft to bake Skype into IE, without plugins
Redmond thinks the Object Real-Time Communications API for WebRTC is ready to roll
Mozilla: Spidermonkey ATE Apple's JavaScriptCore, THRASHED Google V8
Moz man claims the win on rivals' own benchmarks
Microsoft promises Windows 10 will mean two-factor auth for all
Sneak peek at security features Redmond's baking into new OS
FTDI yanks chip-bricking driver from Windows Update, vows to fight on
Next driver to battle fake chips with 'non-invasive' methods
DEATH by PowerPoint: Microsoft warns of 0-day attack hidden in slides
Might put out patch in update, might chuck it out sooner
Ubuntu 14.10 tries pulling a Steve Ballmer on cloudy offerings
Oi, Windows, centOS and openSUSE – behave, we're all friends here
Apple's OS X Yosemite slurps UNSAVED docs into iCloud
Docs, email contacts... shhhlooop, up it goes
prev story

Whitepapers

Cloud and hybrid-cloud data protection for VMware
Learn how quick and easy it is to configure backups and perform restores for VMware environments.
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.
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.
Saudi Petroleum chooses Tegile storage solution
A storage solution that addresses company growth and performance for business-critical applications of caseware archive and search along with other key operational systems.
How to simplify SSL certificate management
Simple steps to take control of SSL certificates across the enterprise, and recommendations centralizing certificate management throughout their lifecycle.