Java XML Node to String toString(Node n)

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

Description

to String

License

Apache License

Declaration

public static String toString(Node n) throws IOException, TransformerException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.IOException;

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;

public class Main {
    private static SAXTransformerFactory transformerFactory;

    public static String toString(Node n) throws IOException, TransformerException {
        TransformerHandler hd = newTransformerHandler();
        Transformer serializer = hd.getTransformer();

        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        DOMSource source = new DOMSource(n);
        StringWriter w = new StringWriter();
        StreamResult result = new StreamResult(w);

        serializer.transform(source, result);

        return w.toString();
    }/*from w w w .j a  v  a2s. c  o m*/

    public static TransformerHandler newTransformerHandler() throws TransformerConfigurationException {
        if (transformerFactory == null) {
            transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        }

        return transformerFactory.newTransformerHandler();
    }
}

Related

  1. toString(final Node node)
  2. toString(final Node xml)
  3. toString(final short nodeType)
  4. toString(Node element)
  5. toString(Node n)
  6. toString(Node node)
  7. toString(Node node)
  8. toString(Node node)
  9. toString(Node node)