Feeds

Groovy: XML without the bloat

Flexible strings

Providing a secure and efficient Helpdesk

Hands on, part 1 You may find this hard to believe, but there was a time before XML hell, when the idea was that XML was going to solve just about every tricky problem in software development. From swapping data between applications or platforms, to storing complex data structures in a portable format - XML was the answer.

Growing up around the same time as XML was Java, which - like XML - has since gone on to shape an industry. If we’re honest, though, it’s never been an easy relationship between these two. Processing XML in Java is a common enough requirement, but it can be extremely verbose, requiring plenty of boilerplate code and all kinds of extraneous scaffolding that obscures what are often very straightforward functions.

That’s where Groovy comes in. As befits a young scripting language for the Java Virtual Machine, Groovy can do XML in a way that is relatively free of bloat and allows the developer to focus on the real problem at hand. In this two-part tutorial I shall look at how Groovy can help in reading and writing XML documents. You can find instructions on installing and running Groovy here, or you can refer back to my earlier article.

At some time or other we’ve probably all written code that just uses strings to write out a fragment of XML. It’s cheap but clunky, but it saves having to instantiate a DOM tree or any of that fiddly stuff. Groovy’s flexible strings allow us to do this very, very simply.

Here’s how we create a fragment of XML that contains a list of names each in an element called "hello", and each with an order attribute:

names=['john','bill','ted']
x=0
frag=''
names.each {
  x++
  frag+="""<hello order="$x">$it</hello>\n"""
}

Running this code in the GroovyConsole, or dumping it into a file called xml.groovy and running it from the command line produces the following output:

<hello order="1">john</hello>
<hello order="2">bill</hello>
<hello order="3">ted</hello>

But that’s only a bunch of strings, there’s no XML declaration, and certainly no way it can be processed as XML. If we do need to turn this into a DOM tree, we can do that easily enough too. Let’s make our hello elements children of a root element called "names" and then turn it into a DOM tree that we can interrogate:

def StringReader s=new StringReader("<names>\n" + frag + "</names>")
def xmldoc=groovy.xml.DOMBuilder.parse(s)
def names=xmldoc.documentElement

println names 

use (groovy.xml.dom.DOMCategory){
    println names.hello[0].text()
    println names.hello.size()
    println names.hello[1].attributes.item(0).text()
}

This code spools out our well-formed XML and the results of some simple tree walking:

<?xml version="1.0" encoding="UTF-8"?>
<names>
<hello order="1">john</hello>
<hello order="2">bill</hello>
<hello order="3">ted</hello>
</names>

john
3
2

It should be clear by now that the combination of Groovy’s convenience methods (from the groovy.xml.* libraries), iterators and powerful string handling capabilities make for very succinct code for creating XML from relatively straightforward data. While the equivalent Java code would take a lot more typing - which wouldn’t be half as readable and easy to follow - so far there’s nothing tremendously taxing here.

Reducing the cost and complexity of web vulnerability management

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
SUSE Linux owner Attachmate gobbled by Micro Focus for $2.3bn
Merger will lead to mainframe and COBOL powerhouse
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
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.
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.
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.
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.
Security for virtualized datacentres
Legacy security solutions are inefficient due to the architectural differences between physical and virtual environments.