【问题标题】:xslt, calculating sum of sum using functionxslt,使用函数计算总和的总和
【发布时间】:2012-10-03 11:57:48
【问题描述】:

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

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

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

谢谢

【问题讨论】:

  • 请编辑问题并提供源 XML 文档(最好是小的),目前缺少。

标签: xml xslt-1.0


【解决方案1】:

我不会使用递归模板,而是使用一个变量。看一下这个例子,我计算每个项目的小计并将其添加到项目中。然后我使用 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>

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

【讨论】:

  • 嗨 Pawel 感谢您抽出宝贵时间,但问题不在于如何计算总数(已经完成),而是如何计算所有客户的所有发票。
  • 如果这是在一个 xml 文档中,那么您可以使用上述(或您的方法)来计算它。如果您有多个文档,您可以使用 document() 函数和转换遍历它们。您可能必须将文件列表传递给样式表
  • 如何使用我的方法计算。
  • 显示输入的xml文档和你想要得到的东西。
  • 请参阅以下链接进行澄清:stackoverflow.com/questions/12907129/…
猜你喜欢
  • 2012-04-19
  • 1970-01-01
  • 2013-11-26
  • 1970-01-01
  • 1970-01-01
  • 2019-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多