Java tutorial
//package com.java2s; //License from project: Apache License import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { public static String logElement(final Element elem, final int level) { String estr = ""; String indentText = " "; String addIndT = ""; // add indent int ind = 0; while (ind < level) { addIndT = addIndT + indentText; ind++; } String name = elem.getNodeName(); estr = "\n" + addIndT + "<" + name + " "; // Attribs NamedNodeMap namedNodeMap = elem.getAttributes(); StringBuilder sb = new StringBuilder(estr); for (int i = 0; i < namedNodeMap.getLength(); i++) { Attr att = (Attr) namedNodeMap.item(i); sb.append(" " + estr + att.getName() + "=\"" + att.getNodeValue() + "\" "); } sb.append(">"); estr = sb.toString(); NodeList pl = elem.getChildNodes(); int index = pl.getLength(); // text nodes if (index > 0) { int i = 0; while (i < index) { Node domNode = pl.item(i); if ((domNode.getNodeType()) == org.w3c.dom.Node.TEXT_NODE) { String Etext = domNode.getNodeValue(); estr = estr + "\n " + addIndT + addIndT + Etext; } i++; } } // Child Elements if (index > 0) { int i = 0; while (i < index) { Node domNode = pl.item(i); if ((domNode.getNodeType()) == org.w3c.dom.Node.ELEMENT_NODE) { Element el = (Element) domNode; estr = estr + logElement(el, level + 1); } i++; } } estr = estr + "\n" + addIndT + "</" + name + ">"; return estr; } }