Here you can find the source of documentToString(Node n)
public static String documentToString(Node n)
//package com.java2s; import org.w3c.dom.*; public class Main { public static String documentToString(Node n) { StringBuilder buffer = new StringBuilder(); if (n == null) return ""; if (n instanceof Document) { buffer.append(documentToString((n).getFirstChild())); } else if (n instanceof Element) { Element element = (Element) n; buffer.append("<"); buffer.append(element.getNodeName()); if (element.hasAttributes()) { NamedNodeMap map = element.getAttributes(); for (int i = 0; i < map.getLength(); i++) { Node attr = map.item(i); buffer.append(" "); buffer.append(attr.getNodeName()); buffer.append("=\""); buffer.append(attr.getNodeValue()); buffer.append("\""); }/*from w ww .ja va 2 s .co m*/ } buffer.append(">"); NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { buffer.append(documentToString(children.item(i))); } buffer.append("</"); buffer.append(element.getNodeName()); buffer.append(">"); } else if (n != null && n.getNodeValue() != null) { buffer.append(n.getNodeValue()); } return buffer.toString(); } }