简体   繁体   中英

parser XML with javascript from java

For this use javax.script.*

Based on

DOMParser is not part of JS but part of Mozilla browser which makes it available to script in the browser using XPConnect. An alternative would be to use built-in E4X.

and

E4X is implemented in Rhino (JavaScript engine written in Java).

try it:

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());
        }
    }
}

but I'm getting error:

sun.org.mozilla.javascript.EcmaError: ReferenceError: "XML" is not defined. (<Unknown source>#2) in <Unknown source> at line number 2

any idea/suggestions ?

The Scripting Programmer guide clearly states that it has excluded E4X (ECMAScript for XML). Check it out in this http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/ .

I had a similar problem, where I had to parse XML using java script and obtain the output. I then used Mozilla Rhino ( https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino ).

It worked well for my situation.

Hope this helps any one who comes across a similar problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM