Java XML Document to Writer writeXML(final Document doc, final Writer writer)

Here you can find the source of writeXML(final Document doc, final Writer writer)

Description

Write the document to a writer.

License

Open Source License

Parameter

Parameter Description
doc the document to write
writer where to write the document

Declaration

public static void writeXML(final Document doc, final Writer writer) 

Method Source Code

//package com.java2s;

import java.io.Writer;

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 {
    /**/*ww  w .  ja v  a  2 s. c om*/
     * Write the document to a writer.
     * 
     * @param doc the document to write
     * @param writer where to write the document
     */
    public static void writeXML(final Document doc, final Writer writer) {
        writeXML(doc, writer, null);
    }

    /**
     * Write the document to a writer.
     * 
     * @param doc the document to write
     * @param writer where to write the document
     * @param encoding if non-null use this as the encoding for the text
     * @throws RuntimeException if a {@link TransformerException} occurs.
     */
    public static void writeXML(final Document doc, final Writer writer, final String encoding) {
        try {
            final TransformerFactory transformerFactory = TransformerFactory.newInstance();
            final Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            if (null != encoding) {
                transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
            }
            final DOMSource source = new DOMSource(doc);
            final StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);
        } catch (final TransformerException e) {
            throw new RuntimeException("Internal error writing xml", e);
        }
    }
}

Related

  1. writeDocument(Document doc, Writer w)
  2. writeDocument(Document document, Writer writer, Integer indent)
  3. writeDocument(PrintWriter w, Document d)
  4. writeDom(Document doc, Writer w)
  5. writeOutDOM(Document doc, Writer writer)