html - Counting unique XML element attributes using XSLT -


i've started using xslt , trying figure out. appreciated.

example xml file

<purchases>     <item id = "1" customer_id = "5">     </item>     <item id = "2" customer_id = "5">     </item>     <item id = "7" customer_id = "4">     </item> </purchases> 

desired html output:

<table>     <tr><th>customer id</th><th>number of items purchased</th></tr>     <tr><td>5</td><td>2</td></tr>     <tr><td>4</td><td>1</td></tr> </table> 

customer id number 5 has bought 2 items. customer id number 4 has bought 1 item.

a possible xslt 1.0 solution be

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform">     <xsl:output method="html" indent="yes"/>      <xsl:key name="kcustomer" match="item" use="@customer_id"/>      <xsl:template match="/">         <xsl:apply-templates />     </xsl:template>      <xsl:template match="purchases">         <xsl:element name="table">             <xsl:element name="tr">                 <xsl:element name="th">customer id</xsl:element>                 <xsl:element name="th">number of items purchased</xsl:element>                 <xsl:for-each select="item[generate-id(.) = generate-id(key('kcustomer', @customer_id))]">                     <xsl:variable name="total" select="count(/purchases/item[@customer_id=current()/@customer_id]/@id)" />                     <xsl:element name="tr">                         <xsl:element name="td">                             <xsl:value-of select="./@customer_id" />                         </xsl:element>                         <xsl:element name="td">                             <xsl:value-of select="$total" />                         </xsl:element>                     </xsl:element>                 </xsl:for-each>             </xsl:element>         </xsl:element>     </xsl:template>  </xsl:stylesheet> 

adopted dimitres answer on how can group , sort based on sum.


as pointed out dimitre purchases template can simplified to

    <xsl:template match="purchases">         <table>             <tr>                 <th>customer id</th>                 <th>number of items purchased</th>             </tr>             <xsl:for-each select="item[generate-id(.) = generate-id(key('kcustomer', @customer_id))]">                 <xsl:variable name="total" select="count(/purchases/item[@customer_id=current()/@customer_id]/@id)" />                     <tr>                         <td>                             <xsl:value-of select="./@customer_id" />                         </td>                         <td>                             <xsl:value-of select="$total" />                         </td>                     </tr>             </xsl:for-each>         </table>     </xsl:template> 

Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -