Java XML String to Document writeDocumentToString(Document document)

Here you can find the source of writeDocumentToString(Document document)

Description

write Document To String

License

Open Source License

Declaration

public static String writeDocumentToString(Document document) 

Method Source Code

//package com.java2s;
/**// ww  w  .ja  v  a  2s .  c  o m
 * Copyright 2015 Yahoo Inc.<br>
 * Licensed under the terms of the MIT license. Please see LICENSE file at the root of this project for terms.
 * <p/>
 *
 * @author yuvalp@yahoo-inc.com
 * 
 */

import java.io.IOException;
import java.io.StringWriter;
import javax.xml.transform.OutputKeys;
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 writeDocumentToString(Document document) {
        try {
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans;
            trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");
            trans.setOutputProperty(
                    "{http://xml.apache.org/xslt}indent-amount", "2");

            StringWriter writer = new StringWriter();
            try {
                StreamResult streamResult = new StreamResult(writer);
                DOMSource source = new DOMSource(document);
                trans.transform(source, streamResult);
            } catch (TransformerException e) {
                e.printStackTrace();
                return null;
            } finally {
                writer.close();
            }
            return writer.toString();

        } catch (TransformerConfigurationException | IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}

Related

  1. toDocument(String string)
  2. toDocument(String xml)
  3. toDocument(String xml)
  4. toXmlDocument(final InputStream inputStream, final String path)
  5. toXMLDocument(String xmlString)
  6. xml2Document(String xml)
  7. xmlNewDocument(final String tagName)
  8. xmlStringToDocument(String xml)
  9. xmlStringToDocument(String xmlInputString)