Java XML Document to String toString(Document doc)

Here you can find the source of toString(Document doc)

Description

Converts an XML document to a formatted XML string.

License

Mozilla Public License

Parameter

Parameter Description
doc The document to format.

Return

Formatted XML document.

Declaration

public static String toString(Document doc) 

Method Source Code

//package com.java2s;
/**/*from   w w w .  j av a2s  .  co  m*/
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 * If a copy of the MPL was not distributed with this file, You can obtain one at
 * http://mozilla.org/MPL/2.0/.
 * 
 * This Source Code Form is also subject to the terms of the Health-Related Additional
 * Disclaimer of Warranty and Limitation of Liability available at
 * http://www.carewebframework.org/licensing/disclaimer.
 */

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
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 {
    /**
     * Converts an XML document to a formatted XML string.
     * 
     * @param doc The document to format.
     * @return Formatted XML document.
     */
    public static String toString(Document doc) {
        if (doc == null) {
            return "";
        }

        try {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(domSource, result);
            return writer.toString();
        } catch (Exception e) {
            return e.toString();
        }
    }
}

Related

  1. toStream(Document document, OutputStream stream)
  2. toString(Document d)
  3. toString(Document doc)
  4. toString(Document doc)
  5. toString(Document doc)
  6. toString(Document doc)
  7. toString(Document doc, String encoding, boolean indent)
  8. toString(Document document)
  9. toString(Document document)