문제

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….

도움이 되었습니까?

해결책

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.

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top