Here you can find the source of writeToFile(File file, Document doc)
public static void writeToFile(File file, Document doc) throws Exception
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileOutputStream; 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; import org.w3c.dom.Element; public class Main { public static void writeToFile(File file, Document doc) throws Exception { String xmlString = getXMLAsString(doc); try (FileOutputStream os = new FileOutputStream(file)) { byte[] xmlStringContent = xmlString.getBytes("UTF-8"); os.write(xmlStringContent);/*from www .j av a2s. c o m*/ os.close(); } } public static String getXMLAsString(Document doc) throws Exception { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); return result.getWriter().toString(); } public static String getXMLAsString(Element eElement) throws Exception { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(eElement); transformer.transform(source, result); return result.getWriter().toString(); } }