Java XML Node to String toString(Node node)

Here you can find the source of toString(Node node)

Description

Write node to a string.

License

Open Source License

Parameter

Parameter Description
node the node to write

Exception

Parameter Description
TransformerException if write failed

Return

string

Declaration

public static String toString(Node node) throws TransformerException 

Method Source Code

//package com.java2s;

import java.io.StringWriter;

import java.io.Writer;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
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 {
    /**//ww w.  j  av  a2  s. co m
     * XML transformer.
     */
    private static ThreadLocal<Transformer> transformers = new ThreadLocal<Transformer>() {
        /**
         * {@inheritDoc}
         */
        @Override
        protected Transformer initialValue() {
            try {
                return TransformerFactory.newInstance().newTransformer();
            } catch (TransformerConfigurationException ex) {
                throw new ExceptionInInitializerError(ex);
            }
        }

    };

    /**
     * Write node to a string.
     * 
     * @param node
     *            the node to write
     * @return string
     * @throws TransformerException
     *             if write failed
     */
    public static String toString(Node node) throws TransformerException {
        DOMSource source = new DOMSource(node);
        Writer w = new StringWriter();
        StreamResult result = new StreamResult(w);
        transformers.get().transform(source, result);
        return w.toString();
    }
}

Related

  1. toString(Node node)
  2. toString(Node node)
  3. toString(Node node)
  4. toString(Node node)
  5. toString(Node node)
  6. toString(Node node)
  7. toString(Node node)
  8. toString(Node node, boolean formatted)
  9. toString(Node node, int level, boolean indent)