xsl-list
[Top] [All Lists]

Re: [xsl] Accessing the Nth Occurrence of an Element

2008-09-16 08:49:38
2008/9/16 David Carlisle <davidc(_at_)nag(_dot_)co(_dot_)uk>:


b) the -or-self part of the // axis is pointless when starting at the root

Actually I think I mislead you there.


two reasons,

firstly //foo  always selects the same nodes as
decendant::foo even if used as a relative xpath. Because there is an
implied child axis in the final step.

//self::foo selects the same nodes as /descendant-or-self::foo


secondly you have to be careful about trees whose root node is an
element. If the current node is such a parentless foo element then
descendant::foo will not select the element, descendant-or-self::foo
will select the element and //foo is an error
 XPDY0050: The root of the tree containing the context item is not a document 
node





<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>


<xsl:variable name="x" as="element()">
 <foo a="1">
 <foo a="2"/>
 <foo a="3"/>
 </foo>
</xsl:variable>


<xsl:template name="main">
 <xsl:for-each select="$x">

<!--A:  <xsl:value-of select="//foo/@a"/>-->
B:  <xsl:value-of select="root()//foo/@a"/>
C:  <xsl:value-of select="root()//self::foo/@a"/>
<!--D:  <xsl:value-of select="/descendant::foo/@a"/>-->
E:  <xsl:value-of select="root()/descendant::foo/@a"/>
<!--F:  <xsl:value-of select="/descendant-or-self::foo/@a"/>-->
G:  <xsl:value-of select="root()/descendant-or-self::foo/@a"/>
 </xsl:for-each>
</xsl:template>

</xsl:stylesheet>



B:  2 3
C:  1 2 3

E:  2 3

G:  1 2 3



Nice... had to read that a few times and think about it, especially
calling root() on variable with type element()...

Consider:

<xsl:variable name="x" as="element()+">
  <foo/>
  <foo/>
</

Calling count($x/root()) returns 2.... which is odd at first, but not
really when each element is both an element and a root node.

Calling count($x[2]/preceding-sibling::*) returns 0, because
effectively the two are separate trees, which helps explain the usual
sibling issues with rootless trees (er, what's the terminology here -
"sequence of element-root nodes"?)

Either way, perhaps it should have read:

b) the -or-self part of the // axis is pointless when starting at a
document node



-- 
Andrew Welch
http://andrewjwelch.com
Kernow: http://kernowforsaxon.sf.net/

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--