Here you can find the source of documentToStream(Document document, OutputStream outputStream, String encoding)
Parameter | Description |
---|---|
document | document to write to the stream |
outputStream | output stream to write the document to |
encoding | the encoding to use when writing |
public static void documentToStream(Document document, OutputStream outputStream, String encoding) throws IOException
//package com.java2s; //License from project: LGPL import java.io.IOException; import java.io.OutputStream; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class Main { /**/*from w ww . ja v a2 s . c o m*/ * Writes the document to the given output stream with the given encoding. * * @param document document to write to the stream * @param outputStream output stream to write the document to * @param encoding the encoding to use when writing */ public static void documentToStream(Document document, OutputStream outputStream, String encoding) throws IOException { Source source = new DOMSource(document); Result result = new StreamResult(outputStream); Transformer transformer; try { transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); if (document.getXmlEncoding() == null) { transformer.setOutputProperty(OutputKeys.ENCODING, encoding); } else { transformer.setOutputProperty(OutputKeys.ENCODING, document.getXmlEncoding()); } transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(source, result); } catch (TransformerFactoryConfigurationError | TransformerException e) { throw new IOException(e.getMessage()); } } /** * Writes the XML {@link Document} to the given output file. * * @param document document to write to the stream * @param outputStream output stream to write the document to */ public static void documentToStream(Document document, OutputStream outputStream) throws IOException { documentToStream(document, outputStream, "UTF-8"); } }