Re: [xsl] best way to divide selected elements?

Subject: Re: [xsl] best way to divide selected elements?
From: Jeni Tennison <mail@xxxxxxxxxxxxxxxx>
Date: Wed, 21 Feb 2001 14:58:41 +0000
Hi Marc,

> I currently have an xsl that takes a directory file list, then based
> on tags within each file, contructs an xml file in which the file
> names are grouped by category, like this:
> I'd like to change it so that if category element is going to
> include more than 20 file elements another category element is
> created:

This is an example of grouping by position.  In general the method for
grouping by position is to find the first node in each group (i.e. the
1st file element, the 21st file element, the 41st file element and so
on) and apply templates to it.  Then, within the applied template,
create the grouping structure (i.e. the category element) and insert
the content for the group (i.e. the relevant file elements).

Getting the first file element in each group involves selecting those
file elements whose position in the category, mod 20, is 1:

  file[position() mod 20 = 1]

So have a template that applies templates only to those initial file

<xsl:template match="category">
   <xsl:apply-templates select="file[position() mod 20 = 1]" />

Now when you match a file element, you know it's one of these.  You
need to create a category element to hold the group:

<xsl:template match="file">

and then insert into it copies of the relevant file elements. The
relevant file elements are the one that you're on and its following 19

  . | following-sibling::file[position() &lt; 20]

You can copy these with xsl:copy-of.  So the complete template is:

<xsl:template match="file">
         select=". | following-sibling::file[position() &lt; 20]" />

I hope that helps,


Jeni Tennison

 XSL-List info and archive:

Current Thread