Java tutorial
//package com.java2s; import java.io.ByteArrayOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; 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; public class Main { public synchronized static String writeXmlToString(Document doc) throws TransformerFactoryConfigurationError, TransformerException { if (doc != null) { ByteArrayOutputStream output = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(output); writeXml(doc, writer, null); return output.toString(); } return null; } public synchronized static void writeXml(Document document, Writer writer, String encoding) throws TransformerFactoryConfigurationError, TransformerException { if (document != null && writer != null) { Source source = new DOMSource(document); Result result = new StreamResult(writer); Transformer xformer = TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.ENCODING, (encoding == null || encoding.isEmpty()) ? "UTF-8" : encoding); xformer.transform(source, result); } } }