Well if you already have the XML document, then you can just read it using java.io classes and then send it as a response line by line and set the content type to text/xml. If you want to build the XML document, then you can build it just like HTML document (but then you'll have to take care of creating a well formed document) or use the W3C API to build a well formed XML document...
Swastik gave a perfect example. Just add setContent("text/xml") to it. Just to add, if you have problems accessing the xml file, then you'll need to give the path to the xml file relative to the root of the web app and then use getServletContext().getRealPath("xmlFileRelativePath/xmlfileName.xml");
Eg if the xml file is in folder /myWebApp/xmls/myXml.xml and myWebApp is the root of the application, then you'll use this statement
Joined: Jan 25, 2008
Hi please look through the following code and tell me if its the right way to create an XML in a servlet.
I placed this code within the doGet method
PrintWriter out = response.getWriter();
out.println("<?xml version='1.0' encoding='ISO-8859-1'?>");
out.println("<compname>" +companyname+ "</compname>");
out.println("<contname>" +contactname+ "</contname>");
out.println("<address>" +address+ "</address>");
out.println("<country>" +country+ "</country>");
When I do this and run my application I am getting a blank page.
Well swastik I don't think that makes too much difference. If you write a JSP page, it also get's translated into a Servlet which contains repeated out.write() method calls. Also the point of concern right now is that Jahnavi is not able to see anything in the response. And whichever way she (I think Jahnavi is a female name) uses, this is not the proper way to do this. W3C DOM API must be used for this purpose. I will make a small program to show how to do when I get time...
You have to somehow read the content of this XML file and flush it to the HttpServeltResponse.getOutputStream() in your doGet()/doPost() method. I have already done this once using JAXB, so this is one of the possible ways. The other way is to do what Swastik suggested.
Instead of using a Reader for the file and a Writer for sending the output, use the FileInputStream directly and copy the bytes to the OutputStream you get from res.getOutputStream(). That way you don't have to worry about the encoding of the XML file (which, invariably, at some point, will NOT be the platform default encoding, at which point the above code will get you in trouble).
Ping & DNS - updated with new look and Ping home screen widget