问题
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