Here you can find the source of toXMLString(Document doc, boolean includeXMLDecl, boolean indent)
public static String toXMLString(Document doc, boolean includeXMLDecl, boolean indent)
//package com.java2s; import java.io.StringWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class Main { public static String toXMLString(Document doc, boolean includeXMLDecl, boolean indent) { String xmlString = null;// ww w. j a v a 2 s . c om try { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, includeXMLDecl ? "yes" : "no"); trans.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); //create string from xml tree StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source, result); xmlString = sw.toString(); } catch (Exception ex) { throw new RuntimeException("Error trying to render DOM to XML String"); } return xmlString; } }