Re: [xsl] (How) can I randomly access the result of a <xsl:for-each select="...?

Subject: Re: [xsl] (How) can I randomly access the result of a <xsl:for-each select="...?
From: Jon Gorman <jonathan.gorman@xxxxxxxxx>
Date: Fri, 14 Oct 2005 16:33:23 -0500
On 10/14/05, Ferdinand Soethe <xsl-list@xxxxxxxxxx> wrote:
> Perhaps I have searched for the wrong key words ...
>
> Is it possible to randomly access each member of the set of nodes
> created by <xsl:for-each select="...

Just want to clarify something, do you need the <xsl:for-each select="" />?

In other words, are you creating new nodes during the <xsl:for-each>
that you wish to examine or are you asking how to access an existing
node set during the <xsl:for-each>.

For example... say we have

<numbers>
<number>3</number>
<number>12</number>
<number>4</number>
<number>2</number>
<number>6</number>
</numbers>

Do you want to do something like create a new set of nodes in the for-each
loop:
say, times each by two and put in element numdoubled, and then manipulate
that?

If so follow Michael Kay's suggestion.

If what you were meaning is that you want to know how to access the
other nodes initially selected in the for-each loop there's different
advice (at least from me).

For example, for some reason you want to print the output of  times
the current number by the the second to previous number for all those
position >= 3

<numbers>
<number>3</number>
<number>12</number>
<number>4</number>
<number>2</number>
<number>6</number>
</numbers>

So it would print out something like 4*3 = 12,  2*12 =24, 6* 4 = 24

In this case there's a couple of ways to do it..
<xsl:for-each select="number">
<xsl:if test="position() >= 3">
<xsl:variable name="pos" select="position()" />
<xsl:value-of select="parent::numbers/number[position() = ($pos -2)] />
...

would probably work.  No idea how slow it'll be though.


Hopefully I haven't made things more confusing.


> I figure that there should be a 'root' element that contains the set
> but I haven't found a way to address that.
>

The parent element of the set?  Again, I'm not sure what you're
talking about.  If you're generating the for-each, you won't have a
"root" element, but after creating a node set out of the variable
you'll be able to go $foo/[xpath here].  If you're looping over a
group of siblings, then use their parent, ie the parent or ancestor
axis.

Jon Gorman

Current Thread