Java XML Document to Stream writeDocument(OutputStream os, Document document)

Here you can find the source of writeDocument(OutputStream os, Document document)

Description

Writes the given document to the given output stream.

License

Open Source License

Parameter

Parameter Description
os an output stream
document a DOM document created by #writeDocument(OutputStream,Document) if something goes wrong

Declaration

public static void writeDocument(OutputStream os, Document document) 

Method Source Code


//package com.java2s;

import java.io.OutputStream;

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;

import org.w3c.dom.ls.LSOutput;

import org.w3c.dom.ls.LSSerializer;

public class Main {
    private static DOMImplementation impl;
    private static DOMImplementationRegistry registry;

    /**//from  w ww  .j  a  v  a 2s. c o m
     * Writes the given document to the given output stream.
     * 
     * @param os
     *            an output stream
     * @param document
     *            a DOM document created by
     *            {@link #writeDocument(OutputStream, Document)} if something
     *            goes wrong
     */
    public static void writeDocument(OutputStream os, Document document) {
        getImplementation();
        DOMImplementationLS implLS = (DOMImplementationLS) impl;

        // serialize to XML
        LSOutput output = implLS.createLSOutput();
        output.setByteStream(os);

        // serialize the document, close the stream
        LSSerializer serializer = implLS.createLSSerializer();
        serializer.getDomConfig().setParameter("format-pretty-print", true);
        serializer.write(document, output);
    }

    /**
     * Creates a new instance of the DOM registry and get an implementation of
     * DOM 3 with Load Save objects.
     * 
     */
    private static void getImplementation() {
        if (registry == null) {
            try {
                registry = DOMImplementationRegistry.newInstance();
            } catch (ClassCastException | ClassNotFoundException | InstantiationException
                    | IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        if (impl == null) {
            impl = registry.getDOMImplementation("Core 3.0 XML 3.0 LS");
        }
    }
}

Related

  1. writeDocument(Document doc, Transformer transformer, OutputStream out)
  2. writeDocument(Document document, OutputStream documentOutputStream)
  3. writeDocument(Document document, OutputStream os)
  4. writeDocument(Document document, OutputStream outputStream)
  5. writeDocument(OutputStream iStream, Element iElement)
  6. writeDocument(OutputStream os, Node node)
  7. writeDocument(OutputStream stream, Document document)
  8. writeDOMDocumentToStream(Document doc, OutputStream stream)
  9. writeOutDocument(OutputStream os, Document doc)