Java XML Document to Stream DocumentToInputStream(Document edoc)

Here you can find the source of DocumentToInputStream(Document edoc)

Description

Converts an org.w3c.dom.Document element to an java.io.InputStream.

License

Open Source License

Parameter

Parameter Description
edoc the org.w3c.dom.Document to be converted

Return

InputStream the InputStream value of the passed doument

Declaration

public static InputStream DocumentToInputStream(Document edoc) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.io.InputStream;

import java.io.PipedInputStream;
import java.io.PipedOutputStream;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

public class Main {
    /**//from w  w w .java 2s .c  om
     * Converts an org.w3c.dom.Document element to an java.io.InputStream.
     * 
     * @param edoc
     *            the org.w3c.dom.Document to be converted
     * @return InputStream the InputStream value of the passed doument
     */
    public static InputStream DocumentToInputStream(Document edoc) throws IOException {

        // Create the input and output for use in the transformation
        final org.w3c.dom.Document doc = edoc;
        final PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream();
        pis.connect(pos);

        (new Thread(new Runnable() {

            public void run() {
                // Use the Transformer.transform() method to save the Document
                // to a StreamResult
                try {
                    TransformerFactory tFactory = TransformerFactory.newInstance();
                    Transformer transformer = tFactory.newTransformer();
                    transformer.setOutputProperty("encoding", "UTF-8");
                    transformer.setOutputProperty("indent", "yes");
                    transformer.transform(new DOMSource(doc), new StreamResult(pos));
                } catch (Exception e) {
                    throw new RuntimeException("Error converting Document to InputStream.  " + e.getMessage());
                } finally {
                    try {
                        pos.close();
                    } catch (IOException e) {

                    }
                }
            }
        }, "IOUtils.DocumentToInputStream(Document edoc)")).start();

        return pis;
    }
}

Related

  1. documentToStream(Document document, OutputStream outputStream, String encoding)
  2. dom2InputStream(Document doc)
  3. dumpDoc(Document domTree, PrintStream out)
  4. dumpToStream(Document doc, OutputStream out)