I\'m trying to parse an XML using Groovy and the ScriptEngine API of Java. The code below does exactly that but I wanted to know if there are any better ways of doing the sa
In order to make ScritpEngine more performant, we could use Compilable interface. The code below is a mix of novelty from Tim's comments and the discussion here.
public static Map> getBookDetails(String scriptXml) {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("groovy");
engine.put("xmlFile", scriptXml);
try {
if (engine instanceof Compilable) {
CompiledScript script = ((Compilable) engine).compile( "new XmlSlurper().parse( xmlFile ).book.findAll().collectEntries { [ (it.@id):[ it.name, it.author ] ] }" );
return (Map>)(script.eval());
}
} catch (ScriptException e) {
e.printStackTrace();
}
return null;
}
Output:
{1=["Catcher In the Rye", J.D. Salinger], 2=["KiteRunner", Khaled Hosseini]}