Java tutorial
//package com.java2s; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; 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 xmlToFile(Document doc, File file) { String xmlString = xmlToString(doc); try { FileWriter w = new FileWriter(file); w.write(xmlString); w.flush(); w.close(); } catch (IOException e) { e.printStackTrace(); } } public static String xmlToString(Document doc) { try { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); return writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); return null; } } }