Search code examples
xmlxsltxslt-2.0xsl-variable

XSLT: Want to use a Variable to Exclude from Sum of Node-set


I have xml that has multiple buckets that are being summed together in a Total

I am using xslt 2.0.....

       <RPTTIME>
            <ATTRTYPE>sickPaid</ATTRTYPE>
            <VALUE>9</VALUE>
        </RPTTIME>
        <RPTTIME>
            <ATTRTYPE>annLeave</ATTRTYPE>
            <VALUE>9</VALUE>
        </RPTTIME>
        <RPTTIME>
            <ATTRTYPE>sickPaid</ATTRTYPE>
            <VALUE>9</VALUE>
        </RPTTIME>
        <RPTTIME>
            <ATTRTYPE>regHour</ATTRTYPE>
            <VALUE>8</VALUE>
        </RPTTIME>

Current code

<xsl:value-of select="sum(./RPTTIME/VALUE)"/>

Results: 35 being reported

I have been asked to exclude some of the values based on the type (annLeave, sickPaid, etc). Desired output in example data would be 8.

This code works

 <xsl:value-of select="sum(./RPTTIME[not(ATTRTYPE=('noMap','otherLeave','leaveWOPay','annLeave','sickPaid','sickNotPaid'))]/VALUE)"/>

I would prefer to use a variable instead. Here is what I am trying but it is being ignored

<xsl:variable name='excludeList'>
  <ATTRTYPE>otherLeave</ATTRTYPE>
  <ATTRTYPE>leaveWOPay</ATTRTYPE>
  <ATTRTYPE>annLeave</ATTRTYPE>
  <ATTRTYPE>sickPaid</ATTRTYPE>
  <ATTRTYPE>sickNotPaid</ATTRTYPE>
</xsl:variable>

 <xsl:value-of select="sum(./RPTTIME[ATTRTYPE != $excludeList]/VALUE)"/>

Result: 35

I have also tried

<xsl:value-of select="sum(./RPTTIME[not(ATTRTYPE = $excludeList)]/VALUE)"/>

Result: 35


Solution

  • I would suggest to just use a string sequence e.g. <xsl:variable name='excludeList' select="'noMap','otherLeave','leaveWOPay','annLeave','sickPaid','sickNotPaid'"/> and then use the previous code but of course with the variable i.e. <xsl:value-of select="sum(./RPTTIME[not(ATTRTYPE=$excludeList)]/VALUE)"/>

    If you want to use your element sequence variable use

    <xsl:variable name='excludeList' as="element()*">
      <ATTRTYPE>otherLeave</ATTRTYPE>
      <ATTRTYPE>leaveWOPay</ATTRTYPE>
      <ATTRTYPE>annLeave</ATTRTYPE>
      <ATTRTYPE>sickPaid</ATTRTYPE>
      <ATTRTYPE>sickNotPaid</ATTRTYPE>
    </xsl:variable>
    

    and of course the variable in place of your previous sequence

    <xsl:value-of select="sum(./RPTTIME[not(ATTRTYPE=$excludeList)]/VALUE)"/>