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