RE: [xsl] Sorting and grouping

Subject: RE: [xsl] Sorting and grouping
From: "George Hill" <ghill@xxxxxxxxxxxx>
Date: Wed, 31 Oct 2001 13:30:09 +1300
Zdenek,

I'm a newbie as far as XSLT is concerned, and I found it helpful to
modify Robert Heller's excellent code to make the groupings a bit more
explicit:

XML:
<?xml version="1.0" encoding="UTF-8"?>
<list>
	<item at="d">dandruff</item>
	<item at="e">egg</item>
	<item at="i">indigo</item>
	<item at="k">kaolin</item>
	<item at="l">light</item>
	<item at="a">apple</item>
	<item at="b">banana</item>
	<item at="b">barracuda</item>
	<item at="b">bunyip</item>
	<item at="b">bonzai</item>
	<item at="k">kiwi</item>
	<item at="b">bingo</item>
	<item at="b">boy</item>
	<item at="b">bet</item>
	<item at="t">tohanga</item>
	<item at="c">cabbage</item>
	<item at="j">jukebox</item>
	<item at="f">fault</item>
	<item at="g">gangrine</item>
	<item at="h">house</item>
	<item at="b">belize</item>
	<item at="c">common</item>
</list>

XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>

 <xsl:output method="xml" />

    <xsl:param name="group">5</xsl:param> <!-- grouping size-->

    <xsl:variable name="items" select="count(//item)"/> <!-- total
number 
of items-->

    <xsl:template match="list">
	 <xsl:value-of select="count(//item)"/> <xsl:text> items in
list, sorted into groups of </xsl:text>
	 <xsl:value-of select="$group"/> 
	    <xsl:apply-templates select="item">
	    	<xsl:sort select="@at" order="ascending"/>
	    </xsl:apply-templates>
	</xsl:template>

    <xsl:template match="item">

		<xsl:choose>
			<xsl:when test="position() mod $group =1">
				<xsl:comment>Begin new
group</xsl:comment>
				<hr></hr>
				<p><xsl:value-of select="position()"/> -
<xsl:apply-templates/></p>
			</xsl:when>
			<xsl:when test="position() mod $group =0">
				<p><xsl:value-of select="position()"/>
-- <xsl:apply-templates/></p>
				<xsl:comment>End group</xsl:comment>
			</xsl:when>
			<xsl:when test="not(position() mod $group =0)
and position() = $items"> 
<!-- last item in sorted list-->
				<p><xsl:value-of select="position()"/>
--- <xsl:apply-templates/></p>
				<xsl:comment>End group</xsl:comment>
			</xsl:when>
			<xsl:otherwise>
			<p><xsl:value-of select="position()"/> ----
<xsl:apply-templates/></p>
			</xsl:otherwise>
			
		</xsl:choose>
		
    </xsl:template>

</xsl:stylesheet>


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread