Java tutorial
//package com.java2s; 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 { /** * Transform a org.w3c.dom.Node to a String * @param node - the Node * @param omitXmlDeclaration - omit XML declaration * @param prettyPrint - apply indentation * @return the String result * @throws TransformerException */ public static String elementToString(Node node, boolean omitXmlDeclaration, boolean prettyPrint) { String result = null; try { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); StringWriter buffer = new StringWriter(); if (omitXmlDeclaration) { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } if (prettyPrint) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } transformer.transform(new DOMSource(node), new StreamResult(buffer)); result = buffer.toString(); } catch (TransformerException e) { throw new RuntimeException(e); } return result; } }