XSLT - 从同一记录中获取2个值的总和

时间:2018-05-12 12:19:06

标签: xml sum xslt-2.0

我无法使用XSLT从XML下面获取TotalPay值。 TotalPay是每个员工的工资类型的总薪酬总和。请参阅下面的XML数据和我想要实现的预期结果。

<---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

1 个答案:

答案 0 :(得分:1)

sum(../Salary/GrossPay)元素的上下文中,这是一个简单的Salary,因为数据似乎已经分组了:

<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