Java tutorial
//package com.java2s; import java.io.File; import java.io.StringWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class Main { public static void saveXMLDocumentAsFile(Document doc, File file) { try { // Indent & Doctype declaration Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // Prepares to write StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); // Output to file result = new StreamResult(file); transformer.transform(source, result); } catch (Exception e) { System.out.println("Error on saving XML file."); e.printStackTrace(); } } }