Java XML Document to String toString(Document doc)

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

Description

Transform a XML Document to String

License

Open Source License

Declaration

public static String toString(Document doc) 

Method Source Code

//package com.java2s;
/**//from   w  ww.j av a  2  s  . c  om
 * Copyright 2017 Institute of Computing Technology, Chinese Academy of Sciences.
 * Licensed under the terms of the Apache 2.0 license.
 * Please see LICENSE file in the project root for terms
 */

import org.w3c.dom.Document;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.io.StringWriter;

public class Main {
    /** Transform a XML Document to String */
    public static String toString(Document doc) {
        try {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            return writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}

Related

  1. toByteArray(final Document document)
  2. toStream(Document document, OutputStream stream)
  3. toString(Document d)
  4. toString(Document doc)
  5. toString(Document doc)
  6. toString(Document doc)
  7. toString(Document doc)
  8. toString(Document doc, String encoding, boolean indent)
  9. toString(Document document)