Java XML Document to String getXML(Document doc)

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

Description

transform the Document into a String

License

Open Source License

Declaration

public static String getXML(Document doc) 

Method Source Code

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

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 {
    /**/*from  w w  w. j a  v  a  2 s.  c  o  m*/
     * transform the Document into a String
     * */
    public static String getXML(Document doc) {
        try {

            DOMSource domSource = new DOMSource(doc);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(
                    "{http://xml.apache.org/xslt}indent-amount", "2");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                    "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter sw = new StringWriter();
            StreamResult sr = new StreamResult(sw);
            transformer.transform(domSource, sr);
            String xml = sw.toString();
            return xml;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }

    }
}

Related

  1. getStringFromDomDocument(org.w3c.dom.Document doc, org.w3c.dom.Document xslt)
  2. getStringFromXMLDocument(Document doc)
  3. getStringFromXPath(Document doc, XPath xpath, String expression)
  4. getStringListFromXPath(Document doc, XPath xpath, String rootNodeExpression, String listExpression)
  5. getStringRepresentation(DocumentFragment df)
  6. getXml(Document doc)
  7. getXML(Document pDocument)
  8. toByteArray(final Document document)
  9. toByteArray(final Document document)