Java XML Document to String xmlDocToString(Document doc)

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

Description

Place the contents of an XML Document into a string object.

License

Open Source License

Parameter

Parameter Description
doc XML Document object.

Return

String contents of the document.

Declaration

public static String xmlDocToString(Document doc) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.StringWriter;

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 org.w3c.dom.Document;

public class Main {
    /**/*from   ww w.  java2s . com*/
     * Place the contents of an XML Document into a string object.
     *
     * @param doc
     *            XML Document object.
     * @return String contents of the document.
     */
    public static String xmlDocToString(Document doc) {

        String output = null;
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer;

        try {
            transformer = transformerFactory.newTransformer();
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));

            output = writer.getBuffer().toString().replaceAll("\n|\r", "");
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return output;
    }
}

Related

  1. writeDocument(Document document)
  2. writeDocumentToStreamResult(Document document, StreamResult outputTarget)
  3. writeToBytes(Document document)
  4. writeXML(Document d)
  5. writeXmlToString(Document xmlDoc)
  6. xmlDocToString(Document doc)
  7. xmlDocumentDecode(final String xmlURI)
  8. xmlDocumentToString(Document doc)
  9. xmlDocumentToString(Document doc)