Java tutorial
//package com.java2s; //License from project: Apache License import org.w3c.dom.Node; public class Main { public static String getpathToRoot(final Node nodeIn) { String path = ""; Node parent = null; int y = 0; if (nodeIn != null) { Node locNode = nodeIn; while (locNode.getParentNode() != null) { parent = locNode.getParentNode(); if (y > 0) { path = ":" + path; } y++; int i = getCurrentPosition(locNode); i = i - 1; // Check to see it has children as otherwise the htmltree has a // problem with expanding leaves. if (nodeIn.hasChildNodes()) { path = i + path; } locNode = parent; } } if (path == null || path.length() == 0) { path = "0"; } return path; } public static int getCurrentPosition(final Node refNode) { if (refNode == null) { return -1; } int counter = 0; Node current = refNode; while (current != null) { if (current.getNodeType() == Node.ELEMENT_NODE) { counter++; } current = current.getPreviousSibling(); } return counter; } }