get XML Content String from Document - Java XML

Java examples for XML:DOM Document

Description

get XML Content String from Document

Demo Code


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

import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

public class Main {
    public static String getXMLContent(Document d) {
        String result = "";
        try {// ww w .j ava  2 s  .co  m
            TransformerFactory tff = TransformerFactory.newInstance();
            Transformer tf = tff.newTransformer();
            tf.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter sw = new StringWriter();
            StreamResult sr = new StreamResult(sw);
            DOMSource source = new DOMSource(d);
            tf.transform(source, sr);
            result = sw.toString();
        } catch (Exception ex) {
            result = "";
        }
        return result;
    }
}

Related Tutorials