3

I work on a web project and at this point I need to pass a hard-coded xml from Java to JavaScript to parse that xml; the problem is that I don't know exactly how to do this. As shown below, my xml is stored in a String variable, so I need to pass this variable to JavaScript. I'm using tomcat as a server.

Java Code - that creates xml:

@Path("/getXml")
@GET
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.TEXT_PLAIN)
public String getXml(@Context HttpServletRequest request) throws TransformerConfigurationException, TransformerException{

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document document = docBuilder.newDocument();
        Element rootElement = document.createElement("news-counts");
        document.appendChild(rootElement);

        int j=12;
        for(int i=1; i<10; i++) {
            Element item = document.createElement("item");
            rootElement.appendChild(item);
            item.setAttribute("count", "" + j);
            item.setAttribute("date", "201408" + "0" + i);
            j=j+2;
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(writer));
        String xmlOutput = writer.getBuffer().toString().replaceAll("\n|\r", "");

       // return Response.status(Status.NOT_ACCEPTABLE).entity("xmlOutput").build();        
       //System.out.println(xmlOutput);

        return xmlOutput;        

    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Searcher.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        return null;
    }

}

JavaScript code - how I tried to acces the xmlOutput variable

function test() {

var r=new XMLHttpRequest();
r.open("GET", "http://localhost:8080/WebApplication6/tavi/searcher/getXml" , false);

r.send(); 
var responseText = r.responseText;
alert(responseText);
}
2
  • 2
    The "easy" way would be to switch to JSON. Commented Aug 13, 2014 at 7:59
  • XMLHttpRequests include a responseXML property for XML responses. Provided a valid response, it should hold a DOM document created from the XML. Commented Aug 13, 2014 at 8:07

3 Answers 3

3

You can parse your xml in javascript by this way -

  var content = xml_string;//your xml string variable                       

    if (typeof content == 'string') {
    content = ( new window.DOMParser() ).parseFromString(content, "text/xml");
    } 
Sign up to request clarification or add additional context in comments.

Comments

3

You can easily use Jquery for parsing xml. Heres another one Easy XML Consumption using jQuery. If you prefer pure javascript look at this thread.

Using Jquery:

    var xml = $.parseXML("<news-counts><item count=\"1\" date=\"2014-08-13 00:00:00\">Stuff</item><item count=\"2\" date=\"2014-08-13 01:01:01\">Bar</item></news-counts>");
    var x = xml.getElementsByTagName('item');
    for(i=0;i<x.length;i++)
        {
        console.log(x.item(i).textContent); //Stuff Bar
        console.log(x.item(i).getAttribute('count')); //1 2
        console.log(x.item(i).getAttribute('date')); //2014-08-13 00:00:00  2014-08-13 01:01:01  
        }  

Using javascript:

var parseXml;
    if (typeof window.DOMParser != "undefined") {
        parseXml = function(xmlStr) {
            return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
        };
    } else if (typeof window.ActiveXObject != "undefined" &&
           new window.ActiveXObject("Microsoft.XMLDOM")) {
        parseXml = function(xmlStr) {
            var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";
            xmlDoc.loadXML(xmlStr);
            return xmlDoc;
        };
    } else {
        throw new Error("No XML parser found");
    }
    var xml = parseXml("<news-counts><item count=\"1\" date='2014-08-13 00:00:00'>Stuff</item><item count=\"2\" date='2014-08-13 00:00:00'>Bar</item></news-counts>");//get attributes or contents after this line

1 Comment

Thank you. I found where "getXml" snapped. I removed the "try-catch" statement and now I can acces my string; it's very odd.
-1

You can parse xml by jQuery. Ref: http://www.jquerybyexample.net/2012/04/read-and-process-xml-using-jquery-ajax.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.