Mega Code Archive

 
Categories / XML / XSLT StyleSheet
 

Select distinct values

File: Data.xml <?xml version="1.0" encoding="iso-8859-1"?> <booklist>    <book>       <title>title 1</title>       <author>author 1</author>       <publisher>publisher 1</publisher>       <isbn>1-11-11111-1</isbn>       <price>6.99</price>       <sales>235</sales>    </book>    <book>       <title>title 2</title>       <author>author 2</author>       <publisher>publisher 2</publisher>       <isbn>0 14 018967 X</isbn>       <price>12.99</price>       <sales>12</sales>    </book> </booklist> File: Transform.xslt <?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"   xmlns:xs="http://www.w3.org/2001/XMLSchema"   exclude-result-prefixes="xs" version="2.0">   <xsl:key name="pub" match="book" use="publisher" />   <xsl:variable name="in" select="/" />   <xsl:variable name="publishers" as="xs:string*"     select="distinct-values(/booklist/book/publisher)" />   <xsl:template match="/">     <html>       <head>         <title>Sales volume by publisher</title>       </head>       <body>         <h1>Sales volume by publisher</h1>         <table id="{generate-id(.)}">           <tr>             <th>Publisher</th>             <th>Total Sales Value</th>           </tr>           <xsl:for-each select="$publishers">             <tr>               <td>                 <xsl:value-of select="." />               </td>               <td>                 <xsl:call-template name="total-sales" />               </td>             </tr>           </xsl:for-each>         </table>       </body>     </html>   </xsl:template>   <xsl:template name="total-sales">     <xsl:param name="publisher" select="." />     <xsl:value-of select="sum($in/key('pub',$publisher)/sales)" />   </xsl:template> </xsl:stylesheet> Output: <html>    <head>       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">       <title>Sales volume by publisher</title>    </head>    <body>       <h1>Sales volume by publisher</h1>       <table id="d2">          <tr>             <th>Publisher</th>             <th>Total Sales Value</th>          </tr>          <tr>             <td>publisher 1</td>             <td>235</td>          </tr>          <tr>             <td>publisher 2</td>             <td>12</td>          </tr>       </table>    </body> </html>