Returns a String representation corresponding to the given XML Document - Java XML

Java examples for XML:DOM Document

Description

Returns a String representation corresponding to the given XML Document

Demo Code


//package com.java2s;

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
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 {
    /**//  w  w  w.  j  ava2 s  . c o  m
     * Returns a String representation corresponding to the given XML Document
     * @param doc The document to be serialized as a String.
     * @param prettyprint Whether the document should be human-readable
     *                    (pretty-printed) or not.
     * @return A String corresponding to the given document.
     */
    public static String stringify(Document doc, boolean prettyprint) {
        try {
            TransformerFactory factory = TransformerFactory.newInstance();
            if (prettyprint)
                factory.setAttribute("indent-number", 2);

            Transformer transformer = factory.newTransformer();
            if (prettyprint)
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            StringWriter writer = new StringWriter();
            Result result = new StreamResult(writer);
            Source source = new DOMSource(doc);
            transformer.transform(source, result);
            writer.flush();
            writer.close();
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Returns a String representation corresponding to the given XML Document
     * @param doc The document to be serialized as a String.
     * @return A String corresponding to the given document.
     */
    public static String stringify(Document doc) {
        return stringify(doc, false);
    }
}

Related Tutorials