[jdom-interest] Xpath support

Steven Shand devel at intrallect.com
Fri Dec 5 00:21:24 PST 2003


> What I would like is a way to get a node's absolute xpath (I'd be
> satisfied if it only worked with Elements, but nodes would be better) -
>
> eg: XPath xpath = element.getXPath();
>
> or   XPath.getXpath(element).
>
> Or is there an easy way to do that already, that I just can't find?

here's something I put together to do just that. It only deals with 
attributes and elements as that's all I had need for. The 
'includeIndices' is something I needed to provide an xpath without 
positioning information.

      public static String generateJDOMXPath( Object node, boolean 
includeIndices )
    {
       String path = null;
	   if ( node instanceof Attribute )
       {
          Attribute attribute = (Attribute) node;
          return generateJDOMXPath( attribute.getParent() ) + "/@@" + 
attribute.getName();
       }
       else if ( node instanceof Element )
       {
          Element element = (Element) node;
          Element parent = element.getParent();

          if ( parent == null || element.isRootElement() )
             return "/" + element.getName();

          Namespace namespace = parent.getNamespace();
          path = generateJDOMXPath( parent ) + '/' + element.getName();
          List siblings = parent.getChildren( element.getName(), 
namespace );
          if ( siblings.size() > 1 && includeIndices )
             path += "[" + ( siblings.indexOf( element ) + 1 ) + "]";
       }

       return path;
    }


Steven Shand




More information about the jdom-interest mailing list