transform Document To String - Java XML

Java examples for XML:XSLT

Description

transform Document To String

Demo Code


//package com.java2s;
import java.io.StringWriter;

import javax.xml.transform.Transformer;
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 {
    public static String transformToString(Document doc) {
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;// w  ww  . ja  v  a  2 s . co  m
        try {
            transformer = tf.newTransformer();
            transformer.transform(domSource, result);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return writer.toString();
    }
}

Related Tutorials