I need to find out how to transform a xml document and save the results using JSP. The JSP will request the source documents of the xml and xsl from a form (ie file already exist on the server) and the JSP would save the results to a file on the server. I can achieve this though a GUI and applying the templates and saving the results to a file bit the same code doesn't work with the JSP. I am using the Java API for xml woth Xalan XSLT processor.

Bozidar Dangubic

Transformer class will take source and write the results to StreamResult which take Writer object as a parameter on one of the constructors. So you can use the Transformer, create DOMSource from your input xml file, create StreamResult from a FileWriter object pointing to a JSP file you want to create and perform a transformation. It is pretty simple. You can also feed this file back to client for download if you do not want to save it on the server (not sure if you need something like this, but you could do it). You could create a StreamResult from HttpServletResponse's OutputStream, cheat the response by providing a bogus content type using setContentType("text/bogus") and when the resulting JSP is fed back to the client, it will not be displayed but download file box will popup prompting the user to save the file to the local machine. Both scenarios are simple to implement.

An of course, here is code snippet. Hope it helps.

TransformerFactory tFactory = TransformerFactory.newInstance();

InputStream xslInStream = yourServlet.getContext().getResourceAsStream("yourXSLFileName") ;

Transformer transformer = tFactory.newTransformer(new StreamSource(xslInStream));

// docOut is org.w3c.Document - your
// input XML
DOMSource docDOMSource = new DOMSource(docOut) ;

FileWriter outWriter = new FileWriter("yourJSP.jsp");			

StreamResult out = new StreamResult(outWriter) ;

transformer.transform(docDOMSource, out) ;