Question

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);
Was it helpful?

Solution

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

OTHER TIPS

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

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 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.

public static InputStream documentToPrettyInputStream(Document document) throws IOException{

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    XMLWriter xmlWriter = new XMLWriter(outputStream, OutputFormat.createPrettyPrint());
    xmlWriter.write(document);
    xmlWriter.close();
    InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

    return inputStream;

}

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top