Evaluating groovy string expression at runtime

If I have code, for example (which does not 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: "Time is $ {new Date ()}

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

Using the code above, I get "Time - $ {(new date ()}" instead of evaluating ...

Thanks for any thoughts ....

+3
source share
2 answers

Hm. First, I tried, like Michael, to use the built-in xml. But it looks like groovy can properly treat them like a GString.

So, I managed to get the work to work differently: 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

groovy , ", .

0

:

def value = element.getAttribute("value")
Binding binding = new Binding()
binding.setVariable("valueExpression", "\"$value\"")
binding.setVariable("a", 10)
binding.setVariable("b", 20)
def interpolatedValue = new GroovyShell(binding).evaluate(
    "return evaluate(valueExpression)")
println ("interpolated Value = $interpolatedValue")

, :

The time is ${new Date()} and $a + $b is ${a+b}

:

interpolated value = The time is Wed Feb 26 10:00:00 2014 and 10 + 20 is 30
0

All Articles