Convert a DOM tree into a String. - Java XML

Java examples for XML:DOM

Description

Convert a DOM tree into a String.

Demo Code


//package com.java2s;
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;

public class Main {
    /**/*from www  .  ja  v a 2s  . c om*/
     * Convert a DOM tree into a String.
     */
    public static String domToString(Document domDoc)
            throws TransformerException, TransformerConfigurationException {
        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer trans = transFact.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter sw = new StringWriter();
        Result result = new StreamResult(sw);

        try {
            trans.transform(new DOMSource(domDoc), result);
        } catch (TransformerException te) {
            System.out.println(te.getMessageAndLocation());
            throw te;
        }
        return sw.toString();
    }
}

Related Tutorials