Java XML Document to String toXML(Document dom)

Here you can find the source of toXML(Document dom)

Description

Exports this DOM as a String

License

Open Source License

Declaration

public static String toXML(Document dom) 

Method Source Code

//package com.java2s;
/*/*w w w .j  a va 2s . c o  m*/
 * $Id: XPathUtils.java 185 2007-02-09 00:16:45Z joshy $
 *
 * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
 * Santa Clara, California 95054, U.S.A. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

import java.io.StringWriter;
import java.util.Properties;
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 {
    /**
     * Exports this DOM as a String
     */
    public static String toXML(Document dom) {
        return toXML(dom, null);
    }

    public static String toXML(Document dom, Properties outputProperties) {
        try {
            DOMSource source = new DOMSource(dom);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            Transformer tx = TransformerFactory.newInstance()
                    .newTransformer();
            if (outputProperties != null) {
                tx.setOutputProperties(outputProperties);
            }
            tx.transform(source, result);
            String s = writer.toString();
            writer.close();
            return s;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related

  1. toString(final Document document, final boolean indent, final boolean omitXmlDeclaration)
  2. toString(Node document)
  3. toStringFromDoc(Document document)
  4. toStructureString(Document document)
  5. toXML(Document document)
  6. toXml(Document domDoc)
  7. toXmlString(Document doc)
  8. toXmlString(Document doc)
  9. toXMLString(Document doc, boolean includeXMLDecl, boolean indent)