Java XML Document to String documentToString(Document doc)

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

Description

Simple method to dump a Document object as a xml string.

License

Apache License

Parameter

Parameter Description
doc the document to convert

Exception

Parameter Description
TransformerException If the document could not be transformed toxml

Return

The document as a xml

Declaration

public static String documentToString(Document doc) throws TransformerException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import org.w3c.dom.Document;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.StringWriter;

public class Main {
    /**/*  w ww .j av a2  s  .c  o m*/
     *  Simple method to dump a Document object as a xml string. Be aware that the
     *  string starts with <?xml ...
     * @param doc the document to convert
     * @return The document as a xml
     * @throws TransformerException If the document could not be transformed to
     * xml
     */
    public static String documentToString(Document doc) throws TransformerException {

        StringWriter writer = new StringWriter();
        getDOCUMENT_TRANSFORMER().transform(new DOMSource(doc), new StreamResult(writer));
        return writer.toString();
    }

    public static Transformer getDOCUMENT_TRANSFORMER() {
        try {
            return TransformerFactory.newInstance().newTransformer();
        } catch (TransformerConfigurationException e) {
            throw new Error("Error initialising default document transformer", e);
        }
    }
}

Related

  1. documentToString(Document d)
  2. documentToString(Document d)
  3. documentToString(Document doc)
  4. documentToString(Document doc)
  5. documentToString(Document doc)
  6. documentToString(Document doc)
  7. documentToString(Document doc)
  8. documentToString(Document doc)
  9. documentToString(Document doc)