Erik
Erik

Reputation: 954

XSLT 2.0: selecting a sub-range of nodes. How?

I have this in the file index.xml, that I transform with XSLT 2.0:

<numberGroup>
  <entry>
    <file>n1.xml</file>
  </entry>
  <entry>
    <file>n2.xml</file>
  </entry>
  <entry>
    <file>n3.xml</file>
  </entry>
  ..... many more entries
</numberGroup>
... and more numberGoups

In the stylesheet I have these two templates:

<xsl:template match="numberGroup">
<xsl:apply-templates select="entry">
  <xsl:with-param name="ngFiles" select="entry/file" tunnel="yes"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="entry">
   <xsl:param name="ngFiles" required="yes" tunnel="yes"/>
   ....
</xsl:template>

Now, select="entry/file" selects all files n1, n2, n3, every time the second template is executed for a "entry/file". However, I need to select only the files up to and including the "entry/file" preceding the file I call the template on. So when the second template executes for n1.xml, ngFiles is empty, when it executes for n2.xml, ngFiles has only n1, and when the template executes for n3.xml, ngFiles has only n1 and n2. I thought maybe I could do something like:

<xsl:with-param name="ngFiles" select="entry/file[0 to .....]" tunnel="yes"/>

in the first template. Any suggestions for the .... ? maybe something with preceding::file or so ?

Upvotes: 1

Views: 181

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122394

Rather than passing a parameter you can retrieve the nodes you want from inside the match="entry" template using

preceding-sibling::entry/file

If you want to tunnel this value into other templates then do:

<xsl:template match="numberGroup">
  <xsl:apply-templates select="entry"/>
</xsl:template>

<xsl:template match="entry">
  <xsl:param name="ngFiles" select="preceding-sibling::entry/file" tunnel="yes"/>
   ....
</xsl:template>

The select on an xsl:param is evaluated in the context of the template that contains it (i.e. the entry element is the current context item) whereas the select on with-param is evaluated in the context of the caller.

Upvotes: 1

Related Questions