title: XML parsing in Java via Groovy
body: <p>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 same. And also if there are any performance implications related to this?</p>
  
  <pre><code>import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.Map;
  
  import javax.script.Invocable;
  import javax.script.ScriptEngine;
  import javax.script.ScriptEngineManager;
  import javax.script.ScriptException;
  /*
  &lt;books&gt;
      &lt;book id="1"&gt;
          &lt;name&gt;"Catcher In the Rye"&lt;/name&gt;
          &lt;author&gt;J.D. Salinger&lt;/author&gt;
      &lt;/book&gt;
      &lt;book id="2"&gt;
        &lt;name&gt;"KiteRunner"&lt;/name&gt;
        &lt;author&gt;Khaled Hosseini&lt;/author&gt;
      &lt;/book&gt;
  &lt;/books&gt;
  */
  
  public class XMLParsing{
    public static void main(String[] args) {
      Map&lt;String, ArrayList&lt;String&gt;&gt; resultMap 
                                       = new HashMap&lt;String, ArrayList&lt;String&gt;&gt;();
      resultMap = getBookDetails("c:\\temp\\book.xml");
      System.out.println(resultMap);
    }
  
  
    public static Map&lt;String ArrayList&lt;String&gt;&gt; getBookDetails(String scriptXml) {
      Map&lt;String, ArrayList&lt;String&gt;&gt; resultMap = 
                                         new HashMap&lt;String, ArrayList&lt;String&gt;&gt;();
      ScriptEngineManager factory = new ScriptEngineManager();
      ScriptEngine engine = factory.getEngineByName("groovy");
      String fact = "import java.util.HashMap;" 
                  + "import java.util.ArrayList;" 
                  + "def getBookInformation(n){" 
                  + "def map1 = new HashMap();" 
                  + "xmlDesc = new XmlSlurper().parse(n);" 
                  + "xmlDesc.book.findAll{it}.each {"
                  + "def list1 = new ArrayList();" 
                  + "def id = it.@id;" 
                  +
                  //"println id;"+
                    "def name = it.name;" 
                  + "def author = it.author;" 
                  + "list1.add(name);" 
                  +  "list1.add(author);" 
                  + "map1.put(id, list1);" 
                  + "};" 
                  + "return map1;}";
      try {
        engine.eval(fact);
        Invocable inv = (Invocable) engine;
        Object[] params = {scriptXml};          
        resultMap = (Map&lt;String,ArrayList&lt;String&gt;&gt;)  
                    inv.invokeFunction("getBookInformation", params);
      } catch (ScriptException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      }
      return resultMap;
    }
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>{1=["Catcher In the Rye", J.D. Salinger], 2=["KiteRunner", Khaled Hosseini]}
  </code></pre>