Java Utililty Methods XML Document to Byte Array

List of utility methods to do XML Document to Byte Array

Description

The list of methods to do XML Document to Byte Array are organized into topic(s).

Method

byte[]asByteArray(Document doc)
Transforms a DOM document to a byte array.
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();
byte[]asByteArray(Document doc, String encoding)
Convert the document to an array of bytes.
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);
...
byte[]documentToByteArray(Document data, Integer indent)
document To Byte Array
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();
...
byte[]documentToByteArray(Document doc)
converts a Document into an UTF-8 encoded byte array
String docString = documentToString(doc);
byte[] stringContent = docString.getBytes(Charset.forName("UTF-8"));
return stringContent;
byte[]documentToBytes(Document doc)
document To Bytes
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMSource source = new DOMSource(doc);
ByteArrayOutputStream output = new ByteArrayOutputStream();
StreamResult result = new StreamResult(output);
transformer.transform(source, result);
byte[] bytes = output.toByteArray();
return bytes;
byte[]dumpToByteArray(Document document)
dump To Byte Array
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult result = new StreamResult(bos);
transformer.transform(new DOMSource(document), result);
byte[] array = bos.toByteArray();
return array;