ar1991
ar1991

Reputation: 25

XSLT - Issue getting sum of 2 values from same record

I am not able to get TotalPay value from below XML using XSLT. TotalPay is the sum of grosspay respective to number of Salary type present for each employee. Please see below XML data and Expected result that i am trying to achieve.

<---XML Data---->

<Payroll_Data>
<EmpId>1000</EmpId>
<FirstName>Mark</FirstName>
<LastName>Henry</LastName>
<Salary>
    <Type>B</Paytype>   
    <GrossPay>1000.50</GrossPay>
</Salary>
<Salary>
    <Type>X</Paytype>   
    <GrossPay>847.50</GrossPay>
</Salary>
</Payroll_Data>
<Payroll_Data>
<EmpId>1001</EmpId>
<FirstName>John</FirstName>
<LastName>Diggle</LastName>
<Salary>
    <Type>B</Paytype>   
    <GrossPay>800.98</GrossPay>
</Salary>
<Salary>
    <Type>X</Paytype>   
    <GrossPay>630.50</GrossPay>
</Salary>
<Salary>
    <Type>Y</Paytype>   
    <GrossPay>600.50</GrossPay>
</Salary>

</Payroll_Data>

<----Expected Result---->
EmpId   FirstName   LastName    Type    GrossPay    TotalPay 
1000    Mark        Henry       B       1000.50     1847.98 (1000.50+847.48)
1000    Mark        Henry       X       847.48      1847.98
1001    John        Diggle      B       800.98      2031.98 (800.98+630.50+600.50)
1001    John        Diggle      X       630.50      2031.98
1001    John        Diggle      Y       600.50      2031.98

Upvotes: 0

Views: 22

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167401

It is a simple sum(../Salary/GrossPay) in the context of a Salary element as it seems the data is already grouped:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="3.0">

  <xsl:output method="text"/>

  <xsl:template match="/">
     <xsl:apply-templates select="//Salary"/>
  </xsl:template>

  <xsl:template match="Salary">
      <xsl:value-of select="../(EmpId, FirstName, LastName), Type, GrossPay, sum(../Salary/GrossPay)" separator="&#9;"/>
      <xsl:text>&#10;</xsl:text>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/3NzcBsW

Upvotes: 1

Related Questions