简体   繁体   中英

Outputting XML on Java Servlet using PrintWriter

I have used this tutorial to convert an ArrayList to XML. My code is successfully outputting XML to the Eclipse console.

Here is a snippet of my code

DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
DocumentBuilder build = dFact.newDocumentBuilder();
Document doc = build.newDocument();

Element root = doc.createElement("Properties");
doc.appendChild(root);

for(House house : house) {

    Element Details = doc.createElement("house");
    root.appendChild(Details);

    Element location = doc.createElement("location");
    location.appendChild(doc.createTextNode(house.getLocation()));
    Details.appendChild(location);

    ...

}

 // Save the document to the disk file
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();

// format the XML nicely
aTransformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");

aTransformer.setOutputProperty(
        "{http://xml.apache.org/xslt}indent-amount", "4");
aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");

DOMSource source = new DOMSource(doc);
StreamResult result =  new StreamResult(System.out);
aTransformer.transform(source, result); 

Instead of outputting this XML to the Eclipse console, I would like to print out the XML on a servlet.

I have done something similar with a jsonObject, using the following code:

PrintWriter out = resp.getWriter();
...
out.print(jsonObject);
out.close();

But I can't seem to work out how to use this method to output my XML.

Please can someone point me in the right direction. Thank you

You should set the content type:

response.setContentType("text/xml; charset=UTF-8"); //you can set the encode you want to charset
PrintWriter out = response.getWriter();
out.print(yourXmlString);

You will use the response.getOutputStream() to write the XML to Servlet output.

StreamResult result =  new StreamResult(response.getOutputStream());

Preferably, you can use a Writer , the response.getWriter() can be used on StreamResult :

StreamResult result =  new StreamResult(response.getWriter());

Also, you will need to set the Content-Type header to text/html; charset=UTF-8 text/html; charset=UTF-8 (and provided your encoding is indeed UTF-8 ).

response.setContentType("text/xml; charset=UTF-8");

I hope this helps.

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