Java tutorial
//package com.java2s; import java.io.File; import java.io.OutputStream; import org.w3c.dom.Document; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSSerializer; public class Main { private static DOMImplementationLS impl; /** * Writes the given document to a file (pretty-printed) * * @param doc Document to serialize * @param file File to write */ public static void writeDocument(Document doc, File file) { if (doc == null) return; LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); writer.writeToURI(doc, file.toURI().toString()); } /** * Writes the given document to a stream (pretty-printed) using utf-8 encoding * * @param doc Document to serialize * @param out the Stream to write to */ public static void writeDocument(Document doc, OutputStream out) { writeDocument(doc, out, "utf-8"); } /** * Writes the given document to a stream (pretty-printed) * * @param doc Document to serialize * @param out the Stream to write to * @param encoding The encoding to use */ public static void writeDocument(Document doc, OutputStream out, String encoding) { if (doc == null) return; LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); LSOutput lsOutput = impl.createLSOutput(); lsOutput.setByteStream(out); lsOutput.setEncoding(encoding); writer.write(doc, lsOutput); } }