giovedì 8 ottobre 2009

Groovy Testing Article

This month the last article in the 'Groovy tools for Java developers' series was published on MokaByte. It was related to Groovy testing, and can be found here. This article is based on a talk I made at the JUG Milano some months ago, that can be found on SlideShare.

Modify XML with groovy

One quite common thing to do when working with XML is to manipulate nodes: remove or rename attributes, changing values, remove or append nodes, and so on.
With Groovy's XmlParser this is quite easy, as explained in the official documentation.
Here are some more complex examples.
Suppose you want to set an attribute value, or to add the attribute if it doesn't exist. You can use this code:
if (!node.attribute('myAtt') {
node.attributes().put('myAtt', 'myValue')
} else {
node.attributes()[myAtt] = 'myValue'

If you want to rename an attribute:
def origAttrs = node.attributes()
if (origAttrs.containsKey(oldAtt)) {
origAttrs[myAtt] = origAttrs[oldAtt]

Suppose you want to replace a child node with another one (in the same position). Since the children() method returns a list of nodes, you can do like this:

def newChild = new Node(node, 'newChild', ['att1': 'val1'], 'New Text')
def indexOfChild = node.children().findIndexOf { == 'oldChildName'}
if (indexOfChild != -1) {
node.children()[indexOfChild] = newChild
newChild.parent = node

In this case we replace the child if there is only one node with that name, otherwise we replace the first one. Of course it's quite easy to replace all the children with a given name.

You can add these methods to a category or to the metaclass of the Node object to have them ready whenever needed.