Feeds

Light reading for XML with Groovy

Intuitive, naturally

  • alert
  • submit to reddit

Combat fraud and increase customer satisfaction

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.

3 Big data security analytics techniques

More from The Register

next story
This time it's 'Personal': new Office 365 sub covers just two devices
Redmond also brings Office into Google's back yard
Batten down the hatches, Ubuntu 14.04 LTS due in TWO DAYS
Admins dab straining server brows in advance of Trusty Tahr's long-term support landing
Inside the Hekaton: SQL Server 2014's database engine deconstructed
Nadella's database sqares the circle of cheap memory vs speed
Microsoft lobs pre-release Windows Phone 8.1 at devs who dare
App makers can load it before anyone else, but if they do they're stuck with it
Oh no, Joe: WinPhone users already griping over 8.1 mega-update
Hang on. Which bit of Developer Preview don't you understand?
Half of Twitter's 'active users' are SILENT STALKERS
Nearly 50% have NEVER tweeted a word
Internet-of-stuff startup dumps NoSQL for ... SQL?
NoSQL taste great at first but lacks proper nutrients, says startup cloud whiz
Windows 8.1, which you probably haven't upgraded to yet, ALREADY OBSOLETE
Pre-Update versions of new Windows version will no longer support patches
IRS boss on XP migration: 'Classic fix the airplane while you're flying it attempt'
Plus: Condoleezza Rice at Dropbox 'maybe she can find ... weapons of mass destruction'
prev story

Whitepapers

Top three mobile application threats
Learn about three of the top mobile application security threats facing businesses today and recommendations on how to mitigate the risk.
Combat fraud and increase customer satisfaction
Based on their experience using HP ArcSight Enterprise Security Manager for IT security operations, Finansbank moved to HP ArcSight ESM for fraud management.
The benefits of software based PBX
Why you should break free from your proprietary PBX and how to leverage your existing server hardware.
Five 3D headsets to be won!
We were so impressed by the Durovis Dive headset we’ve asked the company to give some away to Reg readers.
SANS - Survey on application security programs
In this whitepaper learn about the state of application security programs and practices of 488 surveyed respondents, and discover how mature and effective these programs are.