You don't really have a current node-set at the time that you are
evaluating position(), hence you get weird results.  Note that there is
a different between a node-set and the node's list of siblings.  You are
better off to do something like:
        XPath xp2 = new XPath( "count(preceding-sibling::b)+'1'", null,
null, XPath.SELECT );

-----Original Message-----
From: Hrvoje Simic [mailto:[EMAIL PROTECTED] 
Sent: Monday, January 17, 2005 7:44 AM
To: [EMAIL PROTECTED]
Subject: using position() in an XPath expression within a current node
list


I'm having serious problems with understanding the org.apache.xpath API
regarding XPath use that goes beyond elementary. I've been able to
deduce some of its functionality and performance issues from Javadoc,
experimentation, and Xalan source code, but I'm stuck on using the
"position()" function.

To illustrate, let's say I have input document "doc" containing one
document element containing three subelements:

  <a> <b/> <b/> <b/> </a>

I want to achieve an equivalent of this (written in pseudo-code):

  for-each /a/b print position()

Attempting to write this in Java using org.apache.xpath:

  XPathContext context = new XPathContext();
  XPath xp1 = new XPath( "/a/b", null, null, XPath.SELECT );
  XPath xp2 = new XPath( "position()", null, null, XPath.SELECT );
  XObject xo1 = xp1.execute( context, doc, null );
  Node n;
  for ( NodeIterator i = xo1.nodeset(); (n = i.nextNode()) != null; )
  {
    XObject xo2 = xp2.execute( context, n, null );
    System.out.print( xo2 );
  }

produces output "-1-1-1". The desired output is, of course, "123".

I suppose the code lacks setting current/context node list for the
second expression. I tried to set this with:

  context.pushContextNodeList( (DTMIterator) xo1 );

which alters output to "000". However, this and similar attempts were
just stabs in the dark, without understanding the API.

Could someone please direct me to some comprehensive documentation about
the use of org.apache.xpath that would cover the problem stated above,
or maybe show me a solution in Java with a few pointers on what does
what?


Thankful in advance for any help,

Hrvoje Simic
Inge-Mark d.o.o.
Zagreb, Croatia
mailto:[EMAIL PROTECTED]


Reply via email to