Java XML Node to String nodeToString(final Node node)

Here you can find the source of nodeToString(final Node node)

Description

Converts a Node node to an XML string

License

Open Source License

Parameter

Parameter Description
node the first element

Return

the XML String representation of the node, never null

Declaration

public static String nodeToString(final Node node) 

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.TransformerException;
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 {
    private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory
            .newInstance();//from ww w.  j a v a2s . c  o m

    /**
     * Converts a {@link Node node} to an XML string
     * 
     * @param node the first element
     * @return the XML String representation of the node, never null
     */
    public static String nodeToString(final Node node) {
        try {
            final StringWriter writer = new StringWriter();
            createIndentingTransformer().transform(new DOMSource(node),
                    new StreamResult(writer));
            return writer.toString();
        } catch (final TransformerException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * @return a transformer that indents entries by 4 characters (never null)
     */
    public static Transformer createIndentingTransformer() {
        Transformer transformer;
        try {
            TRANSFORMER_FACTORY.setAttribute("indent-number", 4);
            transformer = TRANSFORMER_FACTORY.newTransformer();
        } catch (final Exception e) {
            throw new IllegalStateException(e);
        }
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(
                "{http://xml.apache.org/xslt}indent-amount", "4");
        return transformer;
    }
}

Related

  1. getXMLStringFragmentFromNode(Node node)
  2. nodeToStr(final Node node)
  3. nodeToString(final Node node)
  4. nodeToString(final Node node)
  5. nodeToString(final Node node)
  6. nodeToString(Node doc)
  7. nodeToString(Node n)
  8. nodeToString(Node n)
  9. nodeToString(Node n)