Java Mailing List Archive

http://www.junlu.com/

Home » Home (12/2007) » JDOM User »

Re: [jdom-interest] Xpath support

Steven Shand

2003-12-05

Replies:


> 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

_______________________________________________
To control your jdom-interest membership:
http://lists.denveronline.net/mailman/options/jdom-interest/youraddr@(protected)


©2008 junlu.com - Jax Systems, LLC, U.S.A.