xslt,使用函数计算总和

时间:2012-10-12 16:00:19

标签: xml xslt-1.0

我有客户发票,我使用以下函数计算此列的价格*数量+总数(对于每个发票和每个客户)              总                                                                                                  

<xsl:template name="sumProducts"> 
    <xsl:param name="pList"/> 
    <xsl:param name="pRunningTotal" select="0"/>         
    <xsl:choose> 
       <xsl:when test="$pList"> 
           <xsl:variable name="varMapPath" select="$pList[1]"/> 
           <xsl:call-template name="sumProducts"> 
               <xsl:with-param name="pList" select="$pList[position() > 1]"/> 
                   <xsl:with-param name="pRunningTotal" select="$pRunningTotal + $varMapPath/unitprice *  $varMapPath/quantity"/>                    
           </xsl:call-template> 
       </xsl:when> 
       <xsl:otherwise> 
           $<xsl:value-of select="format-number($pRunningTotal, '#,##0.00')"/> 
       </xsl:otherwise> 
    </xsl:choose> 
</xsl:template>

我想计算每个客户的所有发票和所有客户的总发票的总额。

谢谢

1 个答案:

答案 0 :(得分:0)

不使用递归模板,而是使用变量。看一下这个例子,我计算每个项目的小计并将其添加到项目中。然后我用sum()函数计算总数:

输入xml:

<root>
  <items>
    <item price="19" quantity="12" />
    <item price="5" quantity="3" />
    <item price="4" quantity="1" />
    <item price="2" quantity="2" />
  </items>
</root>

XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
    <xsl:output method="xml" indent="yes"/>

  <xsl:template match="items">
    <root>
    <xsl:variable name="items-with-sub-totals">
      <xsl:for-each select="item">
        <xsl:copy>
          <xsl:copy-of select="@*"/>
          <xsl:attribute name="sub-total">
            <xsl:value-of select="@price * @quantity"/>
          </xsl:attribute>
        </xsl:copy>
      </xsl:for-each>
    </xsl:variable>

    <debug>
      <xsl:copy-of select="msxsl:node-set($items-with-sub-totals)/*"/>
    </debug>

      <xsl:value-of select="concat('Total:', sum(msxsl:node-set($items-with-sub-totals)/item/@sub-total))" />
    </root>

  </xsl:template>

</xsl:stylesheet>

输出(我添加了一些调试信息以显示变量的外观):

<?xml version="1.0" encoding="utf-8"?>
<root>
  <debug>
    <item price="19" quantity="12" sub-total="228" />
    <item price="5" quantity="3" sub-total="15" />
    <item price="4" quantity="1" sub-total="4" />
    <item price="2" quantity="2" sub-total="4" />
  </debug>
  Total:251
</root>

这种做法与您尝试的方法略有不同,但希望对您有用

相关问题