I am new to groovy - I am hoping this is a simple thing to solve. I am reading in an xml document, and then I am able to access data like this:
def root = new XmlParser().parseText(xmlString)
println root.foo.bar.text()
What I would like to do, is to have loaded the "foo.bar" portion of the path from a file or data base, so that I can do something like this:
def paths = ["foo.bar","tashiStation.powerConverter"] // defined for this example
paths.each {
path ->
println path + "\t" + root.path.text()
}
Obviously the code as written does not work... I thought maybe this would work:
paths.each {
path ->
println path + "\t" + root."${path}".text()
}
...but it doesn't. I based my initial solution on pg 153 of Groovy for DSL where dynamic methods can be created in a similar way.
Thoughts? The ideal solution will not add significant amounts of code and will not add any additional library dependencies. I can always fall back to doing this stuff in Java with JDOM but I was hoping for an elegant groovy solution.
This is very similar to this question from 3 days ago and this question
You basically need to split your path on . and then walk down this list moving through your object graph
def val = path.split( /\./ ).inject( root ) { obj, node -> obj?."$node" }?.text()
println "$path\t$val"
Should do it in this instance :-)
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