Java XML Document to Byte Array asByteArray(Document doc, String encoding)

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

Description

Convert the document to an array of bytes.

License

Open Source License

Parameter

Parameter Description
doc The XML document.
encoding The encoding of the output data.

Exception

Parameter Description
TransformerException If there is an error transforming to text.

Return

The XML document as an array of bytes.

Declaration

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

Method Source Code

//package com.java2s;

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
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 {
    /**/*from   w  w w . ja v a  2 s .  c om*/
     * Convert the document to an array of bytes.
     *
     * @param doc The XML document.
     * @param encoding The encoding of the output data.
     *
     * @return The XML document as an array of bytes.
     *
     * @throws TransformerException If there is an error transforming to text.
     */
    public static byte[] asByteArray(Document doc, String encoding) throws TransformerException {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        StringWriter writer = new StringWriter();
        Result result = new StreamResult(writer);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        return writer.getBuffer().toString().getBytes();
    }
}

Related

  1. asByteArray(Document doc)
  2. documentToByteArray(Document data, Integer indent)
  3. documentToByteArray(Document doc)
  4. documentToBytes(Document doc)
  5. dumpToByteArray(Document document)