Java tutorial
//package com.java2s; import java.io.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; public class Main { /** Write an XML DOM tree to a file * * @param doc the document to write * @param file the file to write to * @throws IOException if a file I/O error occurs */ public static void write(Document doc, File file) throws IOException { try { DOMSource domSource = new DOMSource(doc); FileOutputStream stream = new FileOutputStream(file); // OutputStreamWriter works around indent bug 6296446 in JDK // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446 StreamResult streamResult = new StreamResult(new OutputStreamWriter(stream)); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", new Integer(2)); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.transform(domSource, streamResult); } catch (TransformerException e) { // This exception is never thrown, treat as fatal if it is throw new RuntimeException(e); } } }