Here you can find the source of writeDocToFile(Document doc, String filename)
public static void writeDocToFile(Document doc, String filename) throws Exception
//package com.java2s; //License from project: Apache License import java.io.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.w3c.dom.*; public class Main { public static void writeDocToFile(Document doc, String filename) throws Exception { Source source = new DOMSource(doc); File file = new File(filename); Result result = new StreamResult(file); TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setAttribute("indent-number", 2); Transformer xformer = tFactory.newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT, "yes"); //xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); xformer.transform(source, result); /*OutputFormat format = new OutputFormat(doc); format.setIndenting(true);// ww w . j ava 2s.c om format.setIndent(2); Writer output = new BufferedWriter( new FileWriter(filename) ); XMLSerializer serializer = new XMLSerializer(output, format); serializer.serialize(doc);*/ } }