Java tutorial
//package com.java2s; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; 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.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class Main { private static final String UTF8 = "UTF-8"; private static final String YES = "yes"; private static final String INDENT_AMOUNT = "{http://xml.apache.org/xslt}indent-amount"; private static final ThreadLocal<TransformerFactory> transformerFactory = new ThreadLocal<TransformerFactory>() { protected TransformerFactory initialValue() { return TransformerFactory.newInstance(); }; }; /** * Write an XML document out to a String * @param document - the document to write. * @param indent - the indent level. * @return The XML string */ public static String writeXmlDocumentToString(Document document, int indent) { byte[] bytes = writeXmlDocumentToByteArray(document, indent); try { return new String(bytes, UTF8); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Write an XML document out to a byte array in UTF-8 * @param document - the document to write. * @param indent - the indent level. * @return The XML as a byte array */ public static byte[] writeXmlDocumentToByteArray(Document document, int indent) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); writeXmlDocumentToStream(document, baos, indent); return baos.toByteArray(); } /** * Write an XML document out to an output stream in UTF-8 * @param document - the document to write. * @param outputStream - the stream to which the XML will be written * @param indent - the indent level. */ public static void writeXmlDocumentToStream(Document document, OutputStream outputStream, int indent) { try { Transformer transformer = transformerFactory.get().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, UTF8); if (indent > 0) { transformer.setOutputProperty(OutputKeys.INDENT, YES); transformer.setOutputProperty(INDENT_AMOUNT, Integer.toString(indent)); } Result result = new StreamResult(outputStream); Source source = new DOMSource(document); transformer.transform(source, result); } catch (TransformerException e) { throw new RuntimeException(e); } } }