Java XML Document to String xmlDocumentToString(Document doc)

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

Description

xml Document To String

License

Open Source License

Declaration

public static String xmlDocumentToString(Document doc) 

Method Source Code


//package com.java2s;
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 {
    public static String xmlDocumentToString(Document doc) {

        if (doc == null) {
            return "";
        }/*from   w  w  w. ja  v a2s  .  c o  m*/

        String xmlDocString = "";
        try {
            StringWriter writer = new StringWriter();
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);

            StringBuffer buffer = writer.getBuffer();
            xmlDocString = buffer.toString();

        } catch (TransformerConfigurationException e) {
            System.err.println("Unable to configure XML transformer");
            e.printStackTrace();
        } catch (TransformerException e) {
            System.err.println("Unable to transform XML");
            e.printStackTrace();
        }
        return xmlDocString;
    }
}

Related

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