Apache FOP中模板输出的总和

问题描述

我正在使用Apache FOP生成PDF文档,并且要显示某个值,我必须在多个节点上进行迭代以确定总价格值,然后对该值求和。到目前为止,我有一个遍历数组然后检索预期值的函数,但是当我尝试对结果求和时会出现问题。

    <xsl:function name="foo:buildTotalValue">
    <xsl:param name="items" />

    <xsl:variable name="totals">
      <xsl:for-each select="$items/charge">
        <xsl:call-template name="getTotalPriceNode">
          <xsl:with-param name="itemParam" select="." />
        </xsl:call-template>
      </xsl:for-each>
    </xsl:variable>

    <xsl:value-of select="sum(exsl:node-set($totals))" />
    </xsl:function>

    <xsl:template name="getTotalPriceNode">
    <xsl:param name="itemParam" />
      <xsl:choose>
        <xsl:when test="$itemParam/Recurrance = 'OnceOff'">
          <xsl:value-of select="$itemParam/TotalValue" />
        </xsl:when>
        <xsl:when test="$itemParam/Recurrance = 'Monthly'">
          <xsl:value-of select="$itemParam/TotalValue * $itemParam/Months"/>
        </xsl:when>
        <xsl:otherwise><xsl:value-of select="0" /></xsl:otherwise>
      </xsl:choose>
    </xsl:template>

I'm hoping that when I pass in foo:buildTotalValue with entries like this:

    <Charges>
      <Charge>
        <Recurrance>OnceOff</Recurrance>
        <TotalValue>50.00</TotalValue>
      </Charge>
      <Charge>
        <Recurrance>Monthly</Recurrance>
        <TotalValue>10.00</TotalValue>
        <Months>6</Months>
      </Charge>
    </Charges>

将返回值110.00,但是却出现错误

Cannot convert string "50.0060.00" to double

我尝试在模板中添加<value>或其他内容,然后将其用作exsl:node-set函数的选择器,但这似乎没有什么作用。

解决方法

AFAICT,您的函数存在的问题是,它构建了由被调用模板返回的值的串联字符串,而不是可以转换为节点集并求和的节点树。

尝试更改:

  <xsl:for-each select="$items/charge">
    <xsl:call-template name="getTotalPriceNode">
      <xsl:with-param name="itemParam" select="." />
    </xsl:call-template>
  </xsl:for-each>

收件人:

  <xsl:for-each select="$items/charge">
    <total>
      <xsl:call-template name="getTotalPriceNode">
        <xsl:with-param name="itemParam" select="." />
      </xsl:call-template>
    </total>
  </xsl:for-each>

和:

<xsl:value-of select="sum(exsl:node-set($totals))" />

收件人:

<xsl:value-of select="sum(exsl:node-set($totals)/total)" />

未经测试,因为(请参阅对您问题的评论)。

,

我最终使用了马丁的评论中的建议-xpath 2+表达式遵循:

sum(Charge[Recurrance = 'OnceOff']/TotalValue | Charge[Recurrance = 'Monthly']/(TotalValue * Months))

无需使用功能/模板/节点集(而且用更少的代码)就可以实现我所需要的