XML parsing in Java via Groovy

后端 未结 2 1611
[愿得一人]
[愿得一人] 2021-01-05 22:53

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

2条回答
  •  感情败类
    2021-01-05 23:37

    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]}
    

提交回复
热议问题