<?xml version='1.0' encoding='utf-8' ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  version="1.0">
<xsl:output method="html"/>
<xsl:include href="Style1.xsl" />

<!--  The essence of using the variable instead is very similar to a key table.  In
this solution, all products are put into the variable (which itself is in document order):-->
<xsl:variable name="products" select="//product"/>

<!-- Template for our root rule -->
<xsl:template match="/">
	<xsl:apply-templates/>
</xsl:template>


<!-- Template for our "products" rule -->
<xsl:template match="products">
	<xsl:call-template name="Style1"/>

	<h2>Grouping of Products by Region, then by Product Name </h2>

	<!--Step 2: Visit every product (which essentially is happening when using
	a predicate in the Muenchian method) in sorted order, but only act
	on the first product in document order (again using generate-id() but
	this time with the variable instead of the lookup table): -->

	<xsl:for-each select="$products">

		<!-- Sort Primary key by name in ascending order -->
 	  	<xsl:sort select="name" order="ascending"/>


		<!-- The essence of using the variable instead is very similar to a key table.  In
		this solution, all products are put into the variable (which itself is in document order):-->
 	 	<xsl:variable name="region" select="region"/>

        <xsl:if test="generate-id(.)=generate-id($products[region=$region])">

	    	<!-- Display the region as our table header -->
 	  		<h3><xsl:value-of select="region"/> region</h3>
    
 			<!--Display all nodes for a given region in a table-->
  			<table border="1">
   		   		<tr>
					<th>Product Name</th>
					<th>Price</th>
					<th>Region</th>			
				</tr>


			<!-- The rest is very similar to the Muenchian method, except to grab
 				the products of the same region from the variable instead of the key table -->
	     		<xsl:for-each select="$products[region=$region]">

				<!--Sort our secondary key, product nodes,  by name-->
     			<xsl:sort select="name"/>
	    			<tr>
					<td><xsl:value-of select="name"/></td>
					<td><xsl:value-of select="price"/></td>
					<td><xsl:value-of select="region"/></td>			
				</tr>
   			</xsl:for-each>
 			</table>
			<br/><br/>
       </xsl:if>
	</xsl:for-each>
  
</xsl:template>

</xsl:stylesheet>
