Convert XML Document To String - Java XML

Java examples for XML:XML Document

Description

Convert XML Document To String

Demo Code


//package com.java2s;

import java.io.StringWriter;

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 org.w3c.dom.Document;

public class Main {
    public static String docToString(Document text) {
        StringWriter writer = new StringWriter();
        try {/*from  w ww  . jav  a  2  s.  c o  m*/
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                    "yes");
            transformer.transform(new DOMSource(text), new StreamResult(
                    writer));
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return writer.getBuffer().toString();
    }
}

Related Tutorials