Java XML DOM to String domToString(Node domNode)

Here you can find the source of domToString(Node domNode)

Description

Transforms a DOM node (e.g.

License

Open Source License

Declaration

public static String domToString(Node domNode) 

Method Source Code


//package com.java2s;
/*// w w w  .j av a2  s  .  c  o m
 * SafeOnline project.
 *
 * Copyright 2006-2007 Lin.k N.V. All rights reserved.
 * Lin.k N.V. proprietary/confidential. Use is subject to license terms.
 */

import java.io.*;

import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;

public class Main {
    /**
     * Transforms a DOM node (e.g. DOM element or DOM document) to a String.
     */
    public static String domToString(Node domNode) {

        return domToString(domNode, false);
    }

    /**
     * Transforms a DOM node (e.g. DOM element or DOM document) to a String.
     */
    public static String domToString(Node domNode, boolean indent) {

        try {
            Source source = new DOMSource(domNode);
            StringWriter stringWriter = new StringWriter();
            Result result = new StreamResult(stringWriter);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no");
            transformer.transform(source, result);

            return stringWriter.toString();
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. domNode2String(Node node, boolean indent)
  2. domNodeListToString(NodeList nodeList)
  3. domNodeToString(Node node)
  4. domToString(Node domNode)
  5. domToString(Node domNode, boolean indent)
  6. domToString(Node node)
  7. domToString(Node node, int estSize)