Search code examples
groovygroovyshell

evaluating a groovy string expression at runtime


If I have code such as (which doesn’t work):

def value = element.getAttribute("value")
Binding binding = new Binding();
binding.setVariable("valueExpression", value);
def interpolatedValue = new GroovyShell(binding).evaluate("return valueExpression")
println ("interpolated Value = $interpolatedValue")

and the value from the xml attribute is “The time is ${new Date()}”

how do I get Groovy to evaluate this expression at runtime?

Using the above code I get “The time is ${(new Date()}” instead of an evaluation….

Thanks for any thoughts….


Solution

  • Hmm. Firstly I have tried, as Michael, using inline xml. But It's seems, that groovy can properly treat them as GString.

    So, I have managed make things to work using another way: Templates

    def xml = new XmlSlurper().parse("test.xml")
    def engine = new groovy.text.SimpleTemplateEngine()
    def value = xml.em."@value".each { // iterate over attributes
        println(engine.createTemplate(it.text()).make().toString())
    }
    

    test.xml

    <root>
        <em value="5"></em>
        <em value='"5"'></em>
        <em value='${new Date()}'></em>
        <em value='${ 5 + 4 }'></em>
    </root>
    

    output

    5
    "5"
    Wed Feb 26 23:01:02 MSK 2014
    9
    

    For pure Groovy shell solution, I think we can wrap expression in additional ", but I haven't get any solution yet.