Feeds

Light reading for XML with Groovy

Intuitive, naturally

  • alert
  • submit to reddit

Beginner's guide to SSL certificates

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.

Security for virtualized datacentres

More from The Register

next story
'Windows 9' LEAK: Microsoft's playing catchup with Linux
Multiple desktops and live tiles in restored Start button star in new vids
Not appy with your Chromebook? Well now it can run Android apps
Google offers beta of tricky OS-inside-OS tech
New 'Cosmos' browser surfs the net by TXT alone
No data plan? No WiFi? No worries ... except sluggish download speed
iOS 8 release: WebGL now runs everywhere. Hurrah for 3D graphics!
HTML 5's pretty neat ... when your browser supports it
Greater dev access to iOS 8 will put us AT RISK from HACKERS
Knocking holes in Apple's walled garden could backfire, says securo-chap
NHS grows a NoSQL backbone and rips out its Oracle Spine
Open source? In the government? Ha ha! What, wait ...?
Google extends app refund window to two hours
You now have 120 minutes to finish that game instead of 15
Intel: Hey, enterprises, drop everything and DO HADOOP
Big Data analytics projected to run on more servers than any other app
SUSE Linux owner Attachmate gobbled by Micro Focus for $2.3bn
Merger will lead to mainframe and COBOL powerhouse
prev story

Whitepapers

Providing a secure and efficient Helpdesk
A single remote control platform for user support is be key to providing an efficient helpdesk. Retain full control over the way in which screen and keystroke data is transmitted.
WIN a very cool portable ZX Spectrum
Win a one-off portable Spectrum built by legendary hardware hacker Ben Heck
Storage capacity and performance optimization at Mizuno USA
Mizuno USA turn to Tegile storage technology to solve both their SAN and backup issues.
High Performance for All
While HPC is not new, it has traditionally been seen as a specialist area – is it now geared up to meet more mainstream requirements?
Security and trust: The backbone of doing business over the internet
Explores the current state of website security and the contributions Symantec is making to help organizations protect critical data and build trust with customers.