Published 31 Aug, 2022

Java - how to create an InputStream from a Document or Node

Category Java
Modified : Sep 29, 2022

How can I create an InputStream object from a XML Document or Node object to be used in xstream? I need to replace the ??? with some meaningful code. Thanks.

Document doc = getDocument();
InputStream is = ???;
MyObject obj = (MyObject) xstream.fromXML(is);


There are 4 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Java, Xml, Xstream. These have been categorized in sections for a clear and precise explanation.

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

 public static InputStream document2InputStream(Document document)    throws IOException {
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      OutputFormat outputFormat = new OutputFormat(document);
      XMLSerializer serializer = new XMLSerializer(outputStream, outputFormat);
      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.

public static InputStream documentToPrettyInputStream(Document doc) throws IOException {

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    XMLWriter xmlWriter = new XMLWriter(outputStream, OutputFormat.createPrettyPrint());

    InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

    return inputStream;

If you happen to use DOM4j and you need to print it pretty!