how to create an InputStream from a Document or Node

前端 未结 5 373
后悔当初
后悔当初 2021-01-03 20:35

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.



        
相关标签:
5条回答
  • 2021-01-03 20:44

    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.

    0 讨论(0)
  • 2021-01-03 20:46
     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.

    0 讨论(0)
  • 2021-01-03 20:51
    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!

    0 讨论(0)
  • 2021-01-03 20:56

    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());
    }
    
    0 讨论(0)
  • 2021-01-03 20:59
    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());
    
    0 讨论(0)
提交回复
热议问题