how to create an InputStream from a Document or Node

 public static InputStream document2InputStream(Document document)    throws IOException {
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      OutputFormat outputFormat = new OutputFormat(document);
      XMLSerializer serializer = new XMLSerializer(outputStream, outputFormat);
      serializer.serialize(document);
      return new ByteArrayInputStream(outputStream.toByteArray());
 }

This works if you are using apache Xerces implementation, you can also set format parameter with the output format.


One way to do it: Adapt the Document to a Source with DOMSource. Create a StreamResult to adapt a ByteArrayOutputStream. Use a Transformer from TransformerFactory.newTransformer to copy across the data. Retrieve your byte[] and stream with ByteArrayInputStream.

Putting the code together is left as an exercise.


ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Source xmlSource = new DOMSource(doc);
Result outputTarget = new StreamResult(outputStream);
TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
InputStream is = new ByteArrayInputStream(outputStream.toByteArray());

If you are using Java without any Third Party Libraries, you can create InputStream using below code:

/*
 * Convert a w3c dom node to a InputStream
 */
private InputStream nodeToInputStream(Node node) throws TransformerException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Result outputTarget = new StreamResult(outputStream);
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    t.transform(new DOMSource(node), outputTarget);
    return new ByteArrayInputStream(outputStream.toByteArray());
}

Tags:

Java

Xml

Xstream