Java XML Document Print printDocument(Node _docOrNode, OutputStream _outStream)

Here you can find the source of printDocument(Node _docOrNode, OutputStream _outStream)

Description

Dump a Document or Node -compatible object to the given OutputStream (e.g.

License

Open Source License

Parameter

Parameter Description
_docOrNode Document or Node object
_outStream OutputStream to print on

Exception

Parameter Description
IOException on error

Declaration

public static void printDocument(Node _docOrNode, OutputStream _outStream) throws IOException 

Method Source Code

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

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;

public class Main {
    /**/*w  w w  . j a va2  s .  c om*/
     * Dump a {@link Document} or {@link Node}-compatible object to the given {@link OutputStream} (e.g. System.out).
     *
     * @param _docOrNode {@link Document} or {@link Node} object
     * @param _outStream {@link OutputStream} to print on
     * @throws IOException on error
     */
    public static void printDocument(Node _docOrNode, OutputStream _outStream) throws IOException {
        if (_docOrNode == null || _outStream == null) {
            throw new IOException("Cannot print (on) 'null' object");
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            transformer.transform(new DOMSource(_docOrNode),
                    new StreamResult(new OutputStreamWriter(_outStream, "UTF-8")));
        } catch (UnsupportedEncodingException | TransformerException _ex) {
            throw new IOException("Could not print Document or Node.", _ex);
        }

    }
}

Related

  1. printDocument(File file)
  2. printDocument(final Document doc)
  3. printDocument(Node doc)
  4. printDocumentToStdout(final Document document)
  5. printDocumentTree(Node el)
  6. printDOM(File file, Document doc, String encoding)