问题
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….
回答1:
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.
回答2:
You can also use the following code:
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")
I'm testing the code above using the following element:
The time is ${new Date()} and $a + $b is ${a+b}
The result is:
interpolated value = The time is Wed Feb 26 10:00:00 2014 and 10 + 20 is 30
来源:https://stackoverflow.com/questions/22032263/evaluating-a-groovy-string-expression-at-runtime