简体   繁体   中英

How to access and parse XML file using Java and JavaScript

New to the development scene, please ignore my ignorance if I happen to not make any sense......

I'm trying to access a xml file located in my EJB directory which has to stay there, I need to parse it into a javascript accessible object preferably JSON, to dynamically manipulate it using Javascript / Angular....

using JBOSS, and the file's location is something like

/FOO-ejb/src/main/resources/Config.xml, obviously not accessible through the web since it does not reside under a webserver root directory,

Java is the back-end and I can't seem to find any other ways to access this file to serve it to the front-end,

I'm heading towards the direction of using a service within the EJB to access the file, parse it, then use a REST service to serve the object to the front-end....or write a JSP to read in the file, parse it etc.... are there any other better solutions for this?

Thank you everyone for your time!

I think what you want to do is not achievable since it would mean you'd use Javascript to access the file system which is not possible though HTML5 offers some File API that could work but not to access any file in the file system.

So I'd say that the direction you're heading is the most appropriate and maybe easier because even if you find a way to do it in JavaScript it would be a browser-dependant or some weird workaround that could be broken in future browser's version.

I used Apache Abdera in a Servlet in the past to parse an XML RSS feed and convert it to JSON. Abdera is good at that and worked perfect for me. After getting the JSON object I just had to send it to the response and on the client side I used an AJAX call to the servlet to get the JSON object.

The code was something like this:

try {

    PrintWriter result = response.getWriter();

    // Creates Abdera object and client to process the request.
    Abdera abderaObj = new Abdera();
    AbderaClient client = new AbderaClient(abderaObj);

  AbderaClient.registerTrustManager(); // For SSL connections.

    // Sent the HTTP request of the ATOM Feed through AbderaClient.
    ClientResponse resp = client.get( "http://url/to/your/feed" );

    // if the response was OK...
    if (resp.getType() == ResponseType.SUCCESS) {
        // We get the document as a Feed
        Document<Feed> doc = resp.getDocument();

        // Creates a JSON writer to convert the ATOM Feed
        Writer json = abderaObj.getWriterFactory().getWriter("json");

        // Converts the (XML) ATOM Feed into JSON object 
        doc.writeTo(json, result);
    } 

} catch (Exception ex) {
    ex.printStackTrace(System.out);
}

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