Java XML DOM to String domNode2String(Node node, boolean indent)

Here you can find the source of domNode2String(Node node, boolean indent)

Description

Returns the String-Representation of the given DOM-Node as well-formed DOM-Document.

License

Open Source License

Parameter

Parameter Description
node DOM-Node to print
indent if true resulting XML is endented

Exception

Parameter Description
Exception on error

Return

String - Node as XML-String

Declaration

public static String domNode2String(Node node, boolean indent) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
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.Node;

public class Main {
    /**/*from w  ww. j  ava2  s.  co  m*/
     * Returns the String-Representation of the given DOM-Node as well-formed DOM-Document.
     *
     * @param node DOM-Node to print
     * @param indent if true resulting XML is endented
     * @return <code>String</code> - Node as XML-String
     * @throws Exception on error
     */
    public static String domNode2String(Node node, boolean indent) throws Exception {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no");

        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(node);
        transformer.transform(source, result);

        String xmlString = result.getWriter().toString();

        return xmlString;
    }
}

Related

  1. domNodeListToString(NodeList nodeList)
  2. domNodeToString(Node node)
  3. domToString(Node domNode)
  4. domToString(Node domNode)