Java XML Document to String toString(final Document document, final boolean indent, final boolean omitXmlDeclaration)

Here you can find the source of toString(final Document document, final boolean indent, final boolean omitXmlDeclaration)

Description

to String

License

Open Source License

Declaration

private static String toString(final Document document, final boolean indent, final boolean omitXmlDeclaration)
            throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.StringWriter;

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.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class Main {
    private static String toString(final Document document, final boolean indent, final boolean omitXmlDeclaration)
            throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException {
        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDeclaration ? "yes" : "no");
        transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        final StringWriter stringWriter = new StringWriter();
        final StreamResult streamResult = new StreamResult(stringWriter);

        transformer.transform(new DOMSource(document), streamResult);

        return stringWriter.toString();
    }//from  w  w w .  j  a  v  a2  s.c o m
}

Related

  1. toString(Document document)
  2. toString(Document document)
  3. toString(Document document)
  4. toString(final Document document)
  5. toString(final Document document)
  6. toString(Node document)
  7. toStringFromDoc(Document document)
  8. toStructureString(Document document)
  9. toXML(Document document)