Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSL - sum multiplication of elements

I have a few items like this one:

<item type="goods">
    <quantity unit="pcs">172</quantity>
    <unit-price currency="PLN">420</unit-price>
    <VAT>7</VAT>
</item>

I want to print sum of the cost of this items. So what mathematically:

sum(quantity*unit-price)

How can I do that with xsl? I've tried using variables with for-each loop inside and normal valye-of. but I'm still getting some strange results (I won't add this code since it's just bad).

like image 919
smogg Avatar asked Dec 12 '22 07:12

smogg


1 Answers

XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/root">
    <xsl:text>sum:</xsl:text>

    <xsl:call-template name="sum">
      <xsl:with-param name="nodes" select="item"/>
    </xsl:call-template>
  </xsl:template>

  <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() &gt; 1]" />
        <xsl:with-param name="sum" select="$sum + $current/quantity * $current/unit-price" />
      </xsl:call-template>
    </xsl:if>

    <xsl:if test="not($current)">
      <xsl:value-of select="$sum" />
    </xsl:if>

  </xsl:template>

</xsl:stylesheet>

Input XML:

<root>
  <item type="goods">
    <quantity unit="pcs">1</quantity>
    <unit-price currency="PLN">2</unit-price>
    <VAT>7</VAT>
  </item>
  <item type="goods">
    <quantity unit="pcs">10</quantity>
    <unit-price currency="PLN">20</unit-price>
    <VAT>7</VAT>
  </item>
  <item type="goods">
    <quantity unit="pcs">100</quantity>
    <unit-price currency="PLN">200</unit-price>
    <VAT>7</VAT>
  </item>
</root>

Output:

sum:20202
like image 113
Kirill Polishchuk Avatar answered Dec 24 '22 13:12

Kirill Polishchuk