Java XML Node to String asString(Node node)

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

Description

Format and return the string representation of the specified node and it's children

License

Apache License

Parameter

Parameter Description
node the node to represent

Exception

Parameter Description
TransformerException an exception

Return

a string representation of the specified node

Declaration

public static String asString(Node node) throws TransformerException 

Method Source Code

//package com.java2s;
//License from project: Apache 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 {
    /**//from   ww w .  j a  v  a  2s .  c o  m
     * Format and return the string representation of the specified node and it's children
     * 
     * @param node the node to represent
     * @return a string representation of the specified node
     * @throws TransformerException 
     */
    public static String asString(Node node) throws TransformerException {
        TransformerFactory factory = TransformerFactory.newInstance();
        try {
            factory.setAttribute("indent-number", 4);
        } catch (Throwable t) {
        }
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource source = new DOMSource(node);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        return writer.toString();
    }
}

Related

  1. asString(Element elt)
  2. asString(Node node)
  3. asString(Node node)
  4. asString(XMLStreamReader xmlr)
  5. asXML(Node node)
  6. asXmlString(Node node)