Java XML Document to String getStringFromDocument(Document doc)

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

Description

get String From Document

License

Open Source License

Declaration

public static String getStringFromDocument(Document doc) 

Method Source Code

//package com.java2s;
/*/*from   www. j  a  va 2  s .  c  o  m*/
 * Copyright (c) 2006-2007 Massachusetts General Hospital 
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the i2b2 Software License v1.0 
 * which accompanies this distribution. 
 * 
 * Contributors:
 *       Kavishwar Wagholikar (kavi)
 *       July 4, 2015
 */

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
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 org.w3c.dom.Document;

public class Main {
    public static String getStringFromDocument(Document doc) {
        try {
            doc.normalize();
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            //
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            int indent = 2;
            if (indent > 0) {
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
                        Integer.toString(indent));
            }
            //

            transformer.transform(domSource, result);
            return writer.toString();
        } catch (TransformerException ex) {
            ex.printStackTrace();
            return null;
        }
    }
}

Related

  1. getDocumentAsString(Node node, boolean prettyXml)
  2. getDocumentAsString(Resource resource)
  3. getString(Document document)
  4. getStringFromDoc(org.w3c.dom.Document doc)
  5. getStringFromDocument(Document doc)
  6. getStringFromDOM(Document doc)
  7. getStringFromDomDocument(org.w3c.dom.Document doc, org.w3c.dom.Document xslt)
  8. getStringFromXMLDocument(Document doc)
  9. getStringFromXPath(Document doc, XPath xpath, String expression)