Java XML Document to String xmlDOMDocumentToString(Document doc)

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

Description

Convert XML DOM document to a XML string representation

License

Apache License

Parameter

Parameter Description
doc XML DOM document

Exception

Parameter Description
Exception in error case

Return

XML string

Declaration

public static String xmlDOMDocumentToString(Document doc) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Apache 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 {
    /**// w  w  w  .j  av a 2 s  . c  o m
     * Convert XML DOM document to a XML string representation
     *
     * @param doc
     *            XML DOM document
     * @return XML string
     * @throws Exception
     *             in error case
     */
    public static String xmlDOMDocumentToString(Document doc) throws Exception {
        if (doc == null) {
            throw new RuntimeException("No XML DOM document (null)!");
        }
        StringWriter stringWriter = new StringWriter();
        String strDoc = null;

        try {
            StreamResult streamResult = new StreamResult(stringWriter);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            // transformerFactory.setAttribute("nIndent-number", new Integer(4));
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.transform(new DOMSource(doc.getDocumentElement()), streamResult);
            stringWriter.flush();
            strDoc = stringWriter.toString();
        } catch (Exception e) {
            //            Logger.XMLEval.logState("Parsing of XML DOM document failed: " + e.getMessage(), LogLevel.Error);
            throw e;
        } finally {
            if (stringWriter != null) {
                stringWriter.close();
                stringWriter = null;
            }
        }

        return strDoc;
    }
}

Related

  1. xmlDocumentToString(Document doc)
  2. xmlDocumentToString(Document doc)
  3. xmlDocumentToString(Document document)
  4. xmlDocumentToString(final Document document)
  5. xmlDocumentToString(Node d)
  6. XMLDOMtoString(Document document)
  7. xmlToFile(Document doc, String fileNameToWrite)
  8. XMLtoString(Document doc)
  9. xmlToString(Document doc)