Java XML Document to File writeXMLtoStream(Object osw, Document doc)

Here you can find the source of writeXMLtoStream(Object osw, Document doc)

Description

writes the given XML Document to the given Writer.

License

Apache License

Parameter

Parameter Description
osw - can be either a Java.io.Writer or a java.io.OutputStream
doc - the XML Document to be written to the osw

Exception

Parameter Description
IOException an exception

Declaration

public static void writeXMLtoStream(Object osw, Document doc) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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 {
    /**//from w  w  w.j  a  v  a  2  s . com
     * writes the given XML Document to the given Writer.
     * @param osw - can be either a Java.io.Writer or a java.io.OutputStream
     * @param doc - the XML Document to be written to the osw
     * @throws IOException
     */
    public static void writeXMLtoStream(Object osw, Document doc) throws IOException {
        try {
            TransformerFactory _transformerFactory = TransformerFactory.newInstance();
            //number of spaces per indent
            try {
                _transformerFactory.setAttribute("indent-number", new Integer(4));
            } catch (IllegalArgumentException ex) {
                // Ignore
            }
            Transformer _transformer = _transformerFactory.newTransformer();
            //tell the transformer to format the output xml nicely
            _transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource _source = new DOMSource(doc);
            StreamResult _result;
            if (osw instanceof OutputStream) {
                _result = new StreamResult((OutputStream) osw);
            } else {
                _result = new StreamResult((Writer) osw);
            }
            _transformer.transform(_source, _result);
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }
}

Related

  1. writeXMLFile(Document document, Writer writer)
  2. writeXmlFile(File file, Document document)
  3. writeXmlFile(String fileName, Document document)
  4. WriteXMLFile2(Document doc, String strFilePath)
  5. writeXmlToStream(Document doc, OutputStream stream)