Java tutorial
//package com.java2s; //License from project: Apache License import org.w3c.dom.*; public class Main { public static String nodeTreeToString(Node node) { String strNode = ""; Node nodeIt = node; while (nodeIt != null) { strNode = nodeToString(nodeIt) + strNode; nodeIt = nodeIt.getParentNode(); } return strNode; } public static String nodeToString(Node node) { String strNode = ""; Node nodeIt = node; if (nodeIt instanceof Element) { Element elem = (Element) nodeIt; String strElem = ""; strElem += "<" + elem.getTagName(); NamedNodeMap attribs = elem.getAttributes(); int len = attribs.getLength(); for (int i = 0; i < len; i++) { Attr attr = (Attr) attribs.item(i); strElem += " " + attr.getName() + "=\"" + attr.getValue() + "\""; } strElem += ">"; strNode = strElem + strNode; } else if (nodeIt instanceof CharacterData) { CharacterData charNode = (CharacterData) nodeIt; strNode = charNode.getData() + strNode; } else if (nodeIt instanceof Document) strNode = strNode; // no hacemos nada else strNode = nodeIt.getNodeValue() + strNode; return strNode; } }