Java XML Document to String toString(final Document document)

Here you can find the source of toString(final Document document)

Description

to String

License

Open Source License

Declaration

public static String toString(final Document document) 

Method Source Code


//package com.java2s;
// Licensed under the MIT license. See License.txt in the project root.

import org.w3c.dom.Document;

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 java.io.ByteArrayOutputStream;

public class Main {
    public static String toString(final Document document) {
        try {/*www  .  j  a  v  a  2 s. com*/
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();

            final TransformerFactory tf = TransformerFactory.newInstance();
            final Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
            //http://johnsonsolutions.blogspot.ca/2007/08/xml-transformer-indent-doesnt-work-with.html
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            transformer.transform(new DOMSource(document), new StreamResult(baos));

            final String result = baos.toString();
            return result;
        } catch (final TransformerException e) {
            throw new Error(e);
        }
    }
}

Related

  1. toString(Document document)
  2. toString(Document document)
  3. toString(Document document)
  4. toString(Document document)
  5. toString(final Document document)
  6. toString(final Document document, final boolean indent, final boolean omitXmlDeclaration)
  7. toString(Node document)
  8. toStringFromDoc(Document document)
  9. toStructureString(Document document)