I am init Document object like this:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
After that I am building an XML file by inserting data to the doc object.
Finally I am writing the contents to a file on my computer.
My question is how to write the contents of doc in to a byte[]
?*
This is how i write the content to the XML file:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("changeOut.xml"));
// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class. Flush the contents to the stream using the flush() method. Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
Data serialization is the process of converting an object into a stream of bytes to more easily save or transmit it.
To convert a file to byte array, ByteArrayOutputStream class is used. This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString().
Pass OutputStream instead of File to the StreamResult
constructor.
ByteArrayOutputStream bos=new ByteArrayOutputStream();
StreamResult result=new StreamResult(bos);
transformer.transform(source, result);
byte []array=bos.toByteArray();
This work for me:
public byte[] documentToByte(Document document)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.xml.security.utils.XMLUtils.outputDOM(document, baos, true);
return baos.toByteArray();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With