Here you can find the source of format(Document doc)
public static String format(Document doc) throws Exception
//package com.java2s; //License from project: Apache License import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import com.sun.org.apache.xml.internal.serialize.OutputFormat; import com.sun.org.apache.xml.internal.serialize.XMLSerializer; import org.w3c.dom.Document; public class Main { public static String format(Document doc) throws Exception { OutputFormat format = new OutputFormat(doc); format.setEncoding("UTF-8"); format.setIndenting(true);/*from w ww .java 2 s . c o m*/ format.setIndent(2); format.setOmitXMLDeclaration(true); ByteArrayOutputStream out = new ByteArrayOutputStream(); Writer output = new OutputStreamWriter(out); XMLSerializer serializer = new XMLSerializer(output, format); serializer.serialize(doc); return new String(out.toByteArray(), "UTF-8"); } }