The position() function operates against the current context: In the xpath "/a/b[position()='1']" the current context is the node-list returned by "/a/b". In the case of applying the xpath "position()" against a node from a for-each loop, your current context is a single node, not a node-list, so the return value for position() is technically "undefined".
The position() function does some tricky things. Note that in the following XML: <a><b><c/><c/></b><b><c/></b></a> The xpath "/a/b/c[position()='1']" returns 2 nodes, while the xpath "(/a/b/c)[position()='1']" returns 1 node. In the first case, the position() function operates in the context of each node-list of 'c' elements within a particular 'b' element. In the second case, the parentheses coerce the returned nodes into a single node-list. The position() function then operates relative to that node-list. Now, if only you could *sort* the nodes somehow... ;) -----Original Message----- From: Hrvoje Šimić [mailto:[EMAIL PROTECTED] Sent: Monday, January 17, 2005 11:27 AM To: Robert Houben; [EMAIL PROTECTED] Subject: RE: using position() in an XPath expression within a current node list > 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 ); I know. However, I was aiming for expression "position()" to operate within the context of xp1. The expressions "/a/b" and "position()" are given - how can you use org.apache.xpath to calculate expected results in Java is the question. I'm assuming this is a built-in functionality of the org.apache.xpath because I see Xalan performing exactly the same thing in its implementation of XSLT's for-each.
