Monday, January 18, 2016

Group and Summarize data in XSLT


I was trying to process an order data which has multiple item. My requirement was to group and summarize the data.

I have following input

<soas:Items>
<soas:Item >
<soas:SKU>32779</soas:SKU>
<soas:Quantity>5</soas:Quantity>
<soas:UnitPrice>10</soas:UnitPrice>
</soas:Item>
<soas:Item >
<soas:SKU>30421</soas:SKU>
<soas:Quantity>2</soas:Quantity>
<soas:UnitPrice>10</soas:UnitPrice>
</soas:Item>
<soas:Item >
<soas:SKU>32861</soas:SKU>
<soas:Quantity>1</soas:Quantity>
<soas:UnitPrice>60</soas:UnitPrice>
</soas:Item>
<soas:Items>


I want the summary of all item amount that is summation for price*quanity of all the items

Summary = (Price*Quantity+Price*Quantity+Price*Quantity)=130

I tried to implement it in XSLT 2.0 but that didn't work for me.

I tried it in XSLT 1.1 using XSLT call template and this worked for me.

I tried to capture the value in Amount element, I used the following code

<tns:Amount>
<xsl:call-template name="sum">
<xsl:with-param name="nodes" select="/ns0:Order/ns0:Items/ns0:Item"/>
</xsl:call-template>
</tns:Amount>


<xsl:template name="sum">
<xsl:param name="nodes"/>
<xsl:param name="sum" select="0"/>
<xsl:variable name="current" select="$nodes[1]"/>
<xsl:if test="$current">
<xsl:call-template name="sum">
<xsl:with-param name="nodes" select="$nodes[position() > 1]"/>
<xsl:with-param name="sum" select="$sum + $current/ns0:UnitPrice * $current/ns0:Quantity"/>
</xsl:call-template>
</xsl:if>
<xsl:if test="not($current)">
<xsl:value-of select="$sum"/>
</xsl:if>
</xsl:template>


No comments: