Converting Document object to Byte[]

不羁岁月 提交于 2020-01-31 07:10:46

问题


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

回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/11982753/converting-document-object-to-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!