Mike Pone
Mike Pone

Reputation: 19330

how to create an InputStream from a Document or Node

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

Upvotes: 32

Views: 62680

Answers (5)

Kostadinov
Kostadinov

Reputation: 71

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!

Upvotes: 2

Frank Biel
Frank Biel

Reputation:

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

Upvotes: 9

Giordano Maestro
Giordano Maestro

Reputation: 341

 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.

Upvotes: 3

Gary Kephart
Gary Kephart

Reputation: 4994

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

Upvotes: 60

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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.

Upvotes: 3

Related Questions