Print a DOM document to stdout. - Java XML

Java examples for XML:DOM Document

Description

Print a DOM document to stdout.

Demo Code

/*/*from  w  w  w . j  a v a  2 s .c om*/
    Open Aviation Map
    Copyright (C) 2012-2013 ??kos Mar?y

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation, either version 3 of the
    License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;
import java.io.OutputStream;

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.Document;

public class Main {
    /**
     * Print a DOM document to stdout.
     *
     * @param document the document to print
     */
    public static void printDocument(Document document) {
        serializeDocument(document, System.out);
    }

    /**
     * Serialize a DOM document to an output stream.
     *
     * @param document the document to print
     * @param os the output stream to serialize to.
     */
    public static void serializeDocument(Document document, OutputStream os) {
        try {
            // write the XML document into a file
            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(os);
            transformer.transform(source, result);
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials