Java XML Element Get getElementPath(Element elem)

Here you can find the source of getElementPath(Element elem)

Description

Get the path to a given element.

License

Open Source License

Parameter

Parameter Description
elem Element of interest

Return

XPath-like path to the element

Declaration

public static String getElementPath(Element elem) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012 Firestar Software, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*  ww  w.  j a  v  a 2s . c o  m*/
 *     Firestar Software, Inc. - initial API and implementation
 *
 * Author:
 *     Gabriel Oancea
 *
 *******************************************************************************/

import org.w3c.dom.*;

public class Main {
    /**
     * Get the path to a given element. The path is a simplified version of XPath. It begins with the first element UNDER
     * the document element.
     * 
     * @param elem Element of interest
     * @return XPath-like path to the element
     */
    public static String getElementPath(Element elem) {
        if (elem == null)
            return null;
        StringBuffer sb = new StringBuffer();
        Node parent = null;
        for (Node node = elem; node != null; node = parent) {
            parent = node.getParentNode();
            if ((node instanceof Element) && (parent instanceof Element)) {
                if (sb.length() > 0)
                    sb.insert(0, '/');
                sb.insert(0, node.getNodeName());
            }
        }
        return sb.toString();
    }
}

Related

  1. getElementNamespaces(Element element, Set namespaces)
  2. getElementNamespaceURI(Element element)
  3. getElementNS(Element el, String nsuri, String name)
  4. getElementNS(Element elem, String namespaceUri, String localName)
  5. getElementNS(Element root, Set nsUris, String wantedLocalName)
  6. getElementPath(Element element)
  7. getElementPath(Element element)
  8. getElementPosition(Element element)
  9. getElements(Element aElement)