Converting Document object to Byte[]

Viewed 43634

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);
3 Answers
Related