Java

Grassroots Groovy: Parse XML with XmlSlurper from Java

Posted on by  
Hubert Klein Ikkink

We can introduce Groovy into our Java projects at grassroots level. Even if we aren't allowed to run the Groovy compiler we can use other ways to run Groovy code. As long as we can include the Groovy libraries as a compile dependency than we can already use Groovy from Java. In this post we see how we can use the power of XmlSlurper to parse XML from our Java code.

To execute a Groovy script from we can use a GroovyShell object and invoke the evaluate() method. The evaluate() method can parse a Groovy script as File or Reader object. We can also use a String value to be evaluated. The last statement of the script that is evaluated can be assigned to a Java variable. To pass variables to the script we use the Binding object. This is a map of variables and their values. We assign values to the variables in the Java code and in the Groovy script we can use the variable values.

Continue reading →

shadow-left