为此用途javax.script.*
基于
DOMParser 不是 JS 的一部分,而是 Mozilla 浏览器的一部分,这使得它可用于使用 XPConnect 在浏览器中编写脚本。另一种方法是使用内置的 E4X。
和
E4X 是在 Rhino(用 Java 编写的 JavaScript 引擎)中实现的。
试试看:
import java.io.IOException;
import java.util.Map;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class heshCode {
public static void main(String[] args) throws IOException {
scripter();
}
public static void scripter() {
try {
String Jscript = "var map = {};" + "\n"+
"var x = new XML();" +
"var person = new XML('<person><name>Bob Smith</name><likes><os>Linux</os><browser>Firefox</browser><language>JavaScript</language><language>Python</language></likes></person>');" +
"map[1]=person.name;" +
"map[2]=person['name'];" +
"map[3]=person.likes.browser;" +
"map[4]=person['likes'].browser;";
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine rhinoEngine = manager.getEngineByName("javascript");
Bindings bindings = rhinoEngine
.getBindings(ScriptContext.ENGINE_SCOPE);
rhinoEngine.eval(Jscript.toString());
@SuppressWarnings("unchecked")
Map<String, String> m = (Map<String, String>) bindings.get("map");
for (Map.Entry<String, String> entry : m.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
} catch (ScriptException e) {
System.out.println(e.getMessage());
}
}
}
但我收到错误:
sun.org.mozilla.javascript.EcmaError: ReferenceError: "XML" is not defined. (<Unknown source>#2) in <Unknown source> at line number 2
有什么想法/建议吗?