Java XML Document to String xmlToString(Document doc)

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

Description

Will get an XML Document as a String

License

BSD License

Parameter

Parameter Description
doc XML Document

Exception

Parameter Description

Return

String xml as String

Declaration

public static String xmlToString(Document doc) throws TransformerException 

Method Source Code

//package com.java2s;
/**/*from   w w  w  .  j  a va 2 s  .c om*/
 * Copyright 5AM Solutions Inc
 * Copyright SemanticBits LLC
 * Copyright AgileX Technologies, Inc
 * Copyright Ekagra Software Technologies Ltd
 *
 * Distributed under the OSI-approved BSD 3-Clause License.
 * See http://ncip.github.com/cacis/LICENSE.txt for details.
 */

import org.w3c.dom.Document;

import javax.xml.transform.Transformer;
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 {
    /**
     * Will get an XML Document as a String
     *
     * @param doc XML Document
     * @return String xml as String
     * @throws javax.xml.transform.TransformerException exception
     */
    public static String xmlToString(Document doc) throws TransformerException {
        final Transformer transformer = TransformerFactory.newInstance().newTransformer();

        // initialize StreamResult with File object to save to file
        final StreamResult result = new StreamResult(new StringWriter());
        final DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        return result.getWriter().toString();
    }
}

Related

  1. xmlDOMDocumentToString(Document doc)
  2. XMLDOMtoString(Document document)
  3. xmlToFile(Document doc, String fileNameToWrite)
  4. xmlToString(Document doc)
  5. XMLtoString(Document doc)
  6. xmlToString(Document document)
  7. xmlToString(Document xml)
  8. xmlToString(Document xml)
  9. XMLToString(Document XMLDocument)