title: XSLT advanced math
body: <p>Help me please with math in XSLT.
  I need need to sum price*VAT fields that have the same unit_id.</p>
  
  <p>Input XML:</p>
  
  <pre><code> &lt;Root&gt; 
  &lt;RowSet&gt;
              &lt;unit_id&gt;1&lt;unit_id&gt;
              &lt;price&gt;100&lt;unit_id&gt;
              &lt;VAT&gt;2&lt;VAT&gt; 
  &lt;/RowSet&gt; 
  &lt;RowSet&gt;
              &lt;unit_id&gt;1&lt;unit_id&gt;
              &lt;price&gt;200&lt;unit_id&gt;
              &lt;VAT&gt;3&lt;VAT&gt; 
  &lt;/RowSet&gt; 
  &lt;RowSet&gt;
              &lt;unit_id&gt;2&lt;unit_id&gt;
              &lt;price&gt;300&lt;unit_id&gt;
              &lt;VAT&gt;4&lt;VAT&gt; 
  &lt;/RowSet&gt;
   &lt;/Root&gt;
  </code></pre>
  
  <p>Expected output must be something like that:</p>
  
  <pre><code>&lt;Root&gt;
  &lt;Output&gt;
          &lt;unit_id&gt;1&lt;unit_id&gt;
          &lt;total&gt;800&lt;total&gt; &lt;?-(100*2+200*3)-?&gt;
  &lt;/Output&gt;
  &lt;Output&gt;
          &lt;unit_id&gt;2&lt;unit_id&gt;
          &lt;total&gt;1200&lt;total&gt;  &lt;?-(300*4)-?&gt;
  &lt;/Output&gt;
  &lt;/Root&gt;
  </code></pre>
  
  <p>I have tried sum(price*VAT) in for-each cycle, but it did not help.</p>
  
  <p>I tried to use this: </p>
  
  <pre><code>&lt;Root&gt;
  &lt;xsl:variable name="ID"&gt;
  &lt;xsl:value-of select="unit_id"/&gt;
  &lt;/xsl:variable&gt;                   
  &lt;xsl:for-each select="/Root/RowSet[unit_id = $ID]"&gt;
  &lt;Output&gt;
  &lt;xsl:if test="position() = count (/Root/RowSet[unit_id = $ID])"&gt;
  &lt;total&gt;
  &lt;xsl:value-of select="sum(/Root/RowSet[unit_id = $ID]/price * /Root/RowSet[unit_id = $ID]/VAT)"/&gt;
  &lt;/total&gt;
  &lt;/xsl:if&gt;
  &lt;/Output&gt;
  &lt;/Root&gt;
  </code></pre>
  
  <p>And the wrong output was:</p>
  
  <pre><code>   &lt;Root&gt;
      &lt;Output&gt;
              &lt;unit_id&gt;1&lt;unit_id&gt;
              &lt;total&gt;200&lt;total&gt; &lt;?-(100*2)-?&gt;
      &lt;/Output&gt;
      &lt;Output&gt;
              &lt;unit_id&gt;2&lt;unit_id&gt;
              &lt;total&gt;1200&lt;total&gt;  &lt;?-(300*4)-?&gt;
      &lt;/Output&gt;
      &lt;/Root&gt;
  </code></pre>