tags:

views:

980

answers:

3

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

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.

Tom Hawtin - tackline
+4  A: 
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());
Gary Kephart
It works well, many thanks.
Mike Pone
A: 
/*
 * 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());
}
Frank Biel