I'm working on a project where I need to parse an XML file and perform the exact same code on 100s of different XML Paths/Nodes. My code currently looks like this…
def items = parser.parseText(inputFile.text)
items.item.each { item ->
try {
// do stuff with item.some_node
} catch(Exception ex) {
//exception stuff
}
try {
// do stuff with item.weight_node
} catch(Exception ex) {
//exception stuff
}
try {
// do stuff with item.another_node[3].sub_node
} catch(Exception ex) {
//exception stuff
}
try {
// do stuff with item.some_node
} catch(Exception ex) {
//exception stuff
}
// do this a 100 times or so with other item node paths
}
Since the 'stuff to do' and the exception 'stuff' is the exact same every time and the only thing that changes is the node I'm working with. Because of this I would rather send the node expression to a method or extend the node class like this…
def myMethod(currentNode) {
try {
// do stuff
} catch(Exception ex) {
//exception stuff
}
}
items.item.each { item ->
myMethod(item.some_node)
myMethod(item.weight_node)
myMethod(item.another_node[3].sub_node)
myMethod(item.some_node)
}
// OR
def myProcess(NodeList n){
try {
// do stuff
} catch(Exception ex) {
//exception stuff
}
}
NodeList.metaClass.myProcess = { -> myProcess(delegate) }
items.item.each { item ->
item.some_node.myMethod()
item.weight_node.myMethod()
item.another_node[3].sub_node.myMethod()
item.some_node.myMethod()
}
With the method attempt I can't figure out how to pass the XPath to the method and then use it. With the class extension method it works so long as the node actually exists. If it doesn't I get an error trying to invoke myProcess.
Any ideas?