Convert a document into a formatted readable string. - Java XML

Java examples for XML:DOM Document

Description

Convert a document into a formatted readable string.

Demo Code


//package com.java2s;
import org.w3c.dom.Document;

import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;

public class Main {
    /**/*w  w  w  .j  a  v  a 2 s  . c om*/
     * Convert a document into a formatted readable string.
     * @param document The document to convert into string.
     * @return A String representation of the document.
     */
    public static String convertToString(Document document) {

        try {

            DOMSource domSource = new DOMSource(document);
            StringWriter sw = new StringWriter();
            Result result = new StreamResult(sw);

            // create an instance of TransformerFactory
            TransformerFactory transFact = TransformerFactory.newInstance();
            Transformer trans;
            trans = transFact.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            trans.transform(domSource, result);
            return sw.toString();
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

Related Tutorials