how to create an InputStream from a Document or Node
Solution 1
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());
Solution 2
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.
Solution 3
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.
Solution 4
public static InputStream documentToPrettyInputStream(Document doc) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XMLWriter xmlWriter = new XMLWriter(outputStream, OutputFormat.createPrettyPrint());
xmlWriter.write(doc);
xmlWriter.close();
InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
return inputStream;
}
If you happen to use DOM4j and you need to print it pretty!
abhiyenta
Big Data Engineer working in Spark, Pig and Hive on the Cloudera stack. I am focused on NLP work in spark. I also have experience in Enterprise Integration using OSGI, Apache Camel and Apache Active MQ. In my spare time, I chase my 6 kids around the house.
Updated on May 01, 2020Comments
-
abhiyenta about 4 years
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);