Java XML Document to Byte Array documentToByteArray(Document data, Integer indent)

Here you can find the source of documentToByteArray(Document data, Integer indent)

Description

document To Byte Array

License

Open Source License

Declaration

public static byte[] documentToByteArray(Document data, Integer indent) throws TransformerException 

Method Source Code


//package com.java2s;
/*//  w  ww.  j  a v a2  s .  c o  m
 * (c) Kitodo. Key to digital objects e. V. <contact@kitodo.org>
 *
 * This file is part of the Kitodo project.
 *
 * It is licensed under GNU General Public License version 3 or later.
 *
 * For the full copyright and license information, please read the
 * GPL3-License.txt file that was distributed with this source code.
 */

import java.io.ByteArrayOutputStream;

import java.util.Objects;

import javax.xml.transform.OutputKeys;
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[] documentToByteArray(Document data, Integer indent) throws TransformerException {
        ByteArrayOutputStream result = new ByteArrayOutputStream();

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        if (Objects.nonNull(indent)) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", indent.toString());
        }
        transformer.transform(new DOMSource(data), new StreamResult(result));
        return result.toByteArray();
    }
}

Related

  1. asByteArray(Document doc)
  2. asByteArray(Document doc, String encoding)
  3. documentToByteArray(Document doc)
  4. documentToBytes(Document doc)
  5. dumpToByteArray(Document document)