Here you can find the source of transformXmlToString(Document importPackageDocument)
public static String transformXmlToString(Document importPackageDocument) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException, IOException
//package com.java2s; //License from project: Apache License import java.io.IOException; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; public class Main { public static String transformXmlToString(Document importPackageDocument) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException, IOException {//from w ww. j a v a2 s. c o m TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); StringWriter writer = new StringWriter(); javax.xml.transform.Result result = new StreamResult(writer); Source source = new DOMSource(importPackageDocument); transformer.transform(source, result); writer.close(); String xml = writer.toString(); return xml; } public static String transformXmlToString(Document doc, String encoding) throws ParserConfigurationException, TransformerException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document document = builder.newDocument(); Element e = doc.getDocumentElement(); Node n = document.importNode(e, true); document.appendChild(n); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, encoding); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(document); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); transformer.transform(source, result); return sw.toString(); } }