Java tutorial
//package com.java2s; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class Main { public synchronized static void writeXmlToFile(Document document, File outputFile) throws TransformerFactoryConfigurationError, TransformerException, IOException { if (document != null && outputFile != null) { FileOutputStream fos = new FileOutputStream(outputFile); OutputStreamWriter writer = new OutputStreamWriter(fos); writeXml(document, writer, null); writer.close(); } } public synchronized static void writeXml(Document document, Writer writer, String encoding) throws TransformerFactoryConfigurationError, TransformerException { if (document != null && writer != null) { Source source = new DOMSource(document); Result result = new StreamResult(writer); Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.ENCODING, (encoding == null || encoding.isEmpty()) ? "UTF-8" : encoding); xformer.transform(source, result); } } }