tags:

views:

294

answers:

1

Is there a way to have XmlSlurper get arbitrary elements through a variable? e.g. so I can do something like input file:

<file>
    <record name="some record" />
    <record name="some other record" />
</file>

def xml = new XmlSlurper().parse(inputFile)
String foo = "record"
return xml.{foo}.size()

I've tried using {} and ${} and () how do I escape variables like that? Or isn't there a way? and is it possible to use results from closures as the arguments as well? So I could do something like

String foo = file.record
int numRecords = xml.{foo.find(/.\w+$/)}
+2  A: 

import groovy.xml.*

def xmltxt = """<file>
    <record name="some record" />
    <record name="some other record" />
</file>"""

def xml = new XmlSlurper().parseText(xmltxt)
String foo = "record"
return xml."${foo}".size()
John Wagenleitner
This doesn't work for elements not immediate children of the root. Observe:def xmltxt = """<file> <something> <record name="some record" /> <record name="some other record" /> </something></file>"""def xml = new XmlSlurper().parseText(xmltxt)String foo = "something.record"return xml."${foo}".size()Any other suggestions?
Keegan
I don't know of any good way, you could split the string: def aNode = xmlfoo.split("\\.").each { aNode = aNode."${it}"}return aNode.size()
John Wagenleitner
Yep, chopping the String up works, thanks :)
Keegan