Here you can find the source of toStringFromDoc(Document document)
public static String toStringFromDoc(Document document)
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.io.StringWriter; import java.util.Properties; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; 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 toStringFromDoc(Document document) { String result = null;//from w ww.ja va 2s .co m if (document != null) { StringWriter strWtr = new StringWriter(); StreamResult strResult = new StreamResult(strWtr); TransformerFactory tfac = TransformerFactory.newInstance(); try { javax.xml.transform.Transformer t = tfac.newTransformer(); t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html, // text t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); t.transform(new DOMSource(document.getDocumentElement()), strResult); } catch (Exception e) { System.err.println("XML.toString(Document): " + e); } result = strResult.getWriter().toString(); try { strWtr.close(); } catch (IOException e) { e.printStackTrace(); } } return result; } public static Transformer newTransformer() { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); Properties properties = transformer.getOutputProperties(); properties.setProperty(OutputKeys.ENCODING, "gb2312"); properties.setProperty(OutputKeys.METHOD, "xml"); properties.setProperty(OutputKeys.VERSION, "1.0"); properties.setProperty(OutputKeys.INDENT, "no"); transformer.setOutputProperties(properties); return transformer; } catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); } } }