Parsing XML is fun again- thanks to Groovy

I happened to work on Groovy while I was developing using Gaelyk and I found Groovy lot easier to write- I never thought of the types and this really helped me to make my codeGroov simpler and easier to write. And when you are dealing with RESTful APIs- you ought to be parsing XML,JSON and what not. As a Java programmer- I never enjoyed it. But Groovy really made parsing xml fun again. Let me show you a sample-

def xml = """<students>
    <school>Kendriya Vidyalaya</school>
    <school>Navodaya Vidyalaya</school>
    <subject>Computer Science</subject>
    <school>National Public School</school>
def students = new XmlSlurper().parseText(xml)
students.student.each{ student ->
   print("Name: ${}")
   print("Age: ${student.age}")
   println("School: ${}")
   student.subject.each{subject ->

Most of the lines of code above is for creating the sample XML, if we actually see the code parsing the XML- its 10 lines (with a bit of jazz for the output).


C:>groovy xmlparser.groovy
Name: Raj Age: 16 School: Kendriya Vidyalaya
Subjects: English Physics Chemistry Math
Name: Mohan Age: 17 School: Navodaya Vidyalaya
Subjects: English Physics Chemistry Computer Science
Name: Kiran Age: 16 School: National Public school
Subjects: English Physics Chemistry Biology


And one can see the output above.

The code is pretty self explanatory- We are using the XmlSlurper utility class in the groovy.util package for parsing the XML. The way the XML elements are accessed is somewhat similar to the Xpath notation, just that the “/” is replaced by “.”. One can access the attributes of the xml node by using- node.@attributeName.

Also if the element is missing in the XML and you try to access it- It doesnt throw a NullPointerException, instead it silently prints empty string- This is something I really liked- I need not worry too much about element being present or not.

For more reading-Groovy Recipes: Greasing The Wheels Of Java

Categories: Groovy

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: