Java XML Document to String getStringFromDOM(Document doc)

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

Description

Returns an XML string given a DOM document.

License

Open Source License

Parameter

Parameter Description
doc a parameter

Exception

Parameter Description
Exception an exception

Declaration

private static String getStringFromDOM(Document doc) throws Exception 

Method Source Code

//package com.java2s;
/*/*from   ww  w  .  j  a  va  2  s.  c om*/
 * Title        :  AlchemiXmlUtil.java
 * Package      :  org.gridbus.alchemi.client.util
 * Project      :  AlchemiJavaAPI
 * Description   :  
 * Created on   :  4/08/2005
 * Author      :  Krishna Nadiminti (kna@cs.mu.oz.au)
 * Copyright    :  (c) 2005, Grid Computing and Distributed Systems Laboratory, 
 *                   Dept. of Computer Science and Software Engineering,
 *                   University of Melbourne, Australia.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later  version.
 * See the GNU General Public License (http://www.gnu.org/copyleft/gpl.html)for more details.
 * 
 */

import java.io.ByteArrayOutputStream;

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 {
    /**
     * Returns an XML string given a DOM document.
     * @param doc
     * @return
     * @throws Exception
     */
    private static String getStringFromDOM(Document doc) throws Exception {
        //get the XML from the DOM
        TransformerFactory transFac = TransformerFactory.newInstance();
        Transformer transformer = transFac.newTransformer();
        DOMSource source = new DOMSource(doc);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(bout);
        transformer.transform(source, result);

        String xml = new String(bout.toByteArray());
        bout.close();
        bout = null;
        return xml;
    }
}

Related

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