Java tutorial
//package com.java2s; //License from project: Open Source License import java.io.ByteArrayOutputStream; import java.io.OutputStream; 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 byte[] document2Bytes(Document document, String encode) throws TransformerException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); document2OutputStream(document, encode, baos); return baos.toByteArray(); } public static void document2OutputStream(Document document, String encode, OutputStream os) throws TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty("encoding", encode); transformer.setOutputProperty("indent", "yes"); transformer.transform(source, new StreamResult(os)); } }