Java XML Document to Byte Array asByteArray(Document doc)

Here you can find the source of asByteArray(Document doc)

Description

Transforms a DOM document to a byte array.

License

LGPL

Parameter

Parameter Description
doc DOM document

Exception

Parameter Description

Return

byte array

Declaration

public static byte[] asByteArray(Document doc)
        throws TransformerException 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import org.w3c.dom.Document;
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 java.io.ByteArrayOutputStream;

public class Main {
    private final static TransformerFactory transformerFactory = TransformerFactory
            .newInstance();/*from   w  ww.j av  a2  s  . c om*/

    /**
     * Transforms a DOM document to a byte array.
     * @param doc DOM document
     * @return byte array
     * @throws javax.xml.transform.TransformerException
     */
    public static byte[] asByteArray(Document doc)
            throws TransformerException {
        Transformer transformer = null;
        transformer = transformerFactory.newTransformer();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(bout);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        return bout.toByteArray();
    }
}

Related

  1. asByteArray(Document doc, String encoding)
  2. documentToByteArray(Document data, Integer indent)
  3. documentToByteArray(Document doc)
  4. documentToBytes(Document doc)