16

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 3

29

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();
Sign up to request clarification or add additional context in comments.

Comments

7

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();
}

1 Comment

Do you have dependency details of org.apache.xml.security.utils.XMLUtils.outputDOM ? I got only node support class file
2

Put a ByteArrayOutputStream where you have the File and you should be good.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.