Here you can find the source of documentToString(Document document)
Parameter | Description |
---|---|
document | Document. |
Parameter | Description |
---|---|
IOException | if an error occurs during transformation. |
public static String documentToString(Document document) throws IOException
//package com.java2s; import java.io.IOException; import java.io.StringWriter; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; 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 INDENT_XML = "no"; public static String OMIT_XML_DECLARATION = "yes"; /**/*from www. j av a2 s. co m*/ * Uses a TransformerFactory with an identity transformation to convert a * Document into a String representation of the XML. * * @param document Document. * @return An XML String. * @throws IOException if an error occurs during transformation. */ public static String documentToString(Document document) throws IOException { String xml = null; try { DOMSource dom = new DOMSource(document); StringWriter writer = new StringWriter(); StreamResult output = new StreamResult(writer); // Use Transformer to serialize a DOM TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); // No need for pretty printing transformer.setOutputProperty(OutputKeys.INDENT, INDENT_XML); // XML Declarations unexpected whitespace for legacy AS XMLDocument type, // so we always omit it. We can't tell whether one was present when // constructing the Document in the first place anyway... transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, OMIT_XML_DECLARATION); transformer.transform(dom, output); xml = writer.toString(); } catch (TransformerException te) { throw new IOException("Error serializing Document as String: " + te.getMessageAndLocation()); } return xml; } }