JavaRanch Home    
This page:         last edited 18 June 2010         What's Changed?         Edit

Document To Byte Array   

Another common question is how one gets a representation of a given DOM object as an array of bytes.

Here's a method that returns the byte-array representation of a given org.w3c.dom.Node object (usually an instance of org.w3c.dom.Element or org.w3c.dom.Document):

import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import org.w3c.dom.*;
public class Util {
    public static byte[] doc2bytes(Node node) {
        try {
            Source source = new DOMSource(node);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            StringWriter stringWriter = new StringWriter();
            Result result = new StreamResult(out);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.transform(source, result);
            return out.toByteArray();
        } catch (TransformerConfigurationException e) {
        } catch (TransformerException e) {
        return null;

(See also DocumentToString)

XmlFaq CategoryCodeSamples

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton