Convert an xml Document object to a String - Java XML

Java examples for XML:DOM Document

Description

Convert an xml Document object to a String

Demo Code


//package com.java2s;
import java.io.ByteArrayOutputStream;
import org.w3c.dom.*;

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

public class Main {
    private static Transformer ourTransformer = null;

    /** Convert an xml Document object to a String */
    public static String convertDocumentToString(Document doc) {

        StreamResult sr = new StreamResult(new ByteArrayOutputStream());
        try {/* w  w  w . ja  v a2s  . co  m*/
            ourTransformer.transform(new DOMSource(doc), sr);
        } catch (TransformerException te) {
            System.out.println(te);
        }

        String docAsString = sr.getOutputStream().toString();
        return docAsString;
    }
}

Related Tutorials