Java tutorial
//package com.java2s; /* * Copyright 2006-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.w3c.dom.*; public class Main { /** * Returns the path expression for a given node. * Path expressions look like: Foo.Bar.Poo where elements are * separated with a dot character. * * @param node in DOM tree. * @return the path expression representing the node in DOM tree. */ public static String getNodesPathName(Node node) { final StringBuffer buffer = new StringBuffer(); if (node.getNodeType() == Node.ATTRIBUTE_NODE) { buildNodeName(((Attr) node).getOwnerElement(), buffer); buffer.append("."); buffer.append(node.getLocalName()); } else { buildNodeName(node, buffer); } return buffer.toString(); } /** * Builds the node path expression for a node in the DOM tree. * @param node in a DOM tree. * @param buffer string buffer. */ private static void buildNodeName(Node node, StringBuffer buffer) { if (node.getParentNode() == null) { return; } buildNodeName(node.getParentNode(), buffer); if (node.getParentNode() != null && node.getParentNode().getParentNode() != null) { buffer.append("."); } buffer.append(node.getLocalName()); } }