Java tutorial
//package com.java2s; //License from project: Open Source License import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Vector; import java.util.StringTokenizer; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * print out all distinct paths in an XML subtree * @param el */ public static void writeAllPaths(Element el) { Hashtable<String, String> allPaths = new Hashtable<String, String>(); String path = ""; collectPaths(path, allPaths, el); for (Enumeration<String> en = allPaths.keys(); en.hasMoreElements();) System.out.println("path: " + en.nextElement()); } private static void collectPaths(String path, Hashtable<String, String> allPaths, Element el) { String newPath = path + el.getLocalName() + "/"; allPaths.put(newPath, "1"); for (Iterator<Element> it = childElements(el).iterator(); it.hasNext();) collectPaths(newPath, allPaths, it.next()); } /** * get the name of an XML element, with the namespace prefix stripped off * @param el * @return */ public static String getLocalName(Node el) { String locName = ""; StringTokenizer st = new StringTokenizer(el.getNodeName(), ":"); while (st.hasMoreTokens()) locName = st.nextToken(); return locName; } /** * Vector of child elements of an element */ public static Vector<Element> childElements(Element el) { Vector<Element> res = new Vector<Element>(); NodeList nodes = el.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node nd = nodes.item(i); if (nd instanceof Element) { Element eg = (Element) nd; res.addElement(eg); } } return res; } }