您的Groovy脚本可能是 “ groovy-er” …
这做同样的事情:
String fact = "def getBookInformation(n) {" + " xmlDesc = new XmlSlurper().parse(n)n" + " xmlDesc.book.findAll().collectEntries {n"+ " [ (it.@id):[ it.name, it.author ] ]n" + " }n" + "}" ;确实,您可以使用
GroovyShell而不是JVM脚本引擎,这可以使您了解:
import java.util.ArrayList;import java.util.Map;import groovy.lang.Binding ;import groovy.lang.GroovyShell ;public class XMLParsing { public static void main(String[] args) { Map<String, ArrayList<String>> resultMap = getBookDetails("test.xml"); System.out.println(resultMap); } public static Map<String, ArrayList<String>> getBookDetails( String scriptXml ) { Binding b = new Binding() ; b.setVariable( "xmlFile", scriptXml ) ; GroovyShell shell = new GroovyShell( b ) ; Object ret = shell.evaluate( "new XmlSlurper().parse( xmlFile ).book.findAll().collectEntries { [ (it.@id):[ it.name, it.author ] ] }" ) ; return (Map<String, ArrayList<String>>)ret ; }}


