Java tutorial
//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 { /** * 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); } } }