Java: Saving StreamResult to a file Java: Saving StreamResult to a file xml xml

Java: Saving StreamResult to a file


Your StreamResult should be created on the basis of a file, e.g.

StreamResult sr = new StreamResult(new File("/my/file.xml"));

If you give your Transformer such a StreamResult, it will write its result directly into the file you specified.


I am not familiar with the API... but does this link give you what you are after?

Transformer transformer = TransformerFactory.newInstance().newTransformer();transformer.setOutputProperty(OutputKeys.INDENT, "yes");//initialize StreamResult with File object to save to fileStreamResult result = new StreamResult(new StringWriter());DOMSource source = new DOMSource(doc);transformer.transform(source, result);String xmlString = result.getWriter().toString();System.out.println(xmlString);