Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Document object to Byte[]

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);
like image 678
Michael A Avatar asked Aug 16 '12 07:08

Michael A


People also ask

How do you convert an object into a byte?

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.

What is the process used to convert an object to a stream of bytes?

Data serialization is the process of converting an object into a stream of bytes to more easily save or transmit it.

How do I get bytes from Fileoutputstream?

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().


2 Answers

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();
like image 91
KV Prajapati Avatar answered Sep 24 '22 18:09

KV Prajapati


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();
}
like image 36
Adrian Avatar answered Sep 24 '22 18:09

Adrian