首页 > 解决方案 > 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>在模板中添加 a 或其他内容,然后将其用作exsl:node-set函数的选择器,但似乎没有什么不同。

标签: xsltapache-fop

解决方案


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)" />

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


推荐阅读