Java tutorial
//package com.java2s; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactoryConfigurationError; import org.w3c.dom.Document; import com.sun.org.apache.xml.internal.serialize.OutputFormat; import com.sun.org.apache.xml.internal.serialize.XMLSerializer; public class Main { public static String formatDocument(Document document) throws TransformerFactoryConfigurationError, TransformerException, IOException { OutputFormat format = new OutputFormat(document, "UTF-8", true); format.setLineWidth(160); // format.setIndenting(true); format.setIndent(2); // format.setEncoding("UTF-8"); Writer out = new StringWriter(); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(document); return out.toString(); } }