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+$/)}
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()
This answer offers a code example, and owes a lot to John W's comment in his answer.
Consider this:
import groovy.util.*
def xml = """<root>
<element1>foo</element1>
<element2>bar</element2>
<items>
<item>
<name>a</name>
<desc>b</desc>
</item>
<item>
<name>c</name>
<desc>x</desc>
</item>
</items>
</root>"""
def getNodes = { doc, path ->
def nodes = doc
path.split("\\.").each { nodes = nodes."${it}" }
return nodes
}
def resource = new XmlSlurper().parseText(xml)
def xpaths = ['/root/element1','/root/items/item/name']
xpaths.each { xpath ->
def trimXPath = xpath.replace("/root/", "").replace("/",".")
println "xpath = ${trimXPath}"
getNodes(resource, trimXPath).each { println it }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With