当我打印总和时,它会在xsl中打印出Nan

时间:2013-01-31 10:34:49

标签: xslt

我试图打印总和,但它会打印每个值的总和。我想得到总和。如何在xsl中使用全局变量

作为获得总和的一个例子,我们可以写sum = sum + value;值是我们得到的新值,sum是已经存在的值。我注意到它总是在xsl中被覆盖。

这是我使用的代码

<xsl:template match="Top">
  <xsl:if test="position() &lt;= 10">


    <xsl:variable name="items"
             select="/TopHoldings/TopHoldingsEntry
             [@Type='Company Name||Co||Se||F Weight (%)||Benchmark weight (%)']
             [@Date='8/31/2011']" />

    <xsl:variable name="totalMarks" 
         select="format-number(substring(substring-after(@Value,'||||'),1,10),'#.#') + 
                 format-number(substring(substring-after(@Value,'||||'),1,10),'#.#')"/>
    <xsl:value-of select="$totalMarks" />

  </xsl:if>
</xsl:template>
我做错了哪里? xml代码

<TopHoldings Currency="xxx">
          <TopHoldingsEntry Type="CName||C||S||Fund Weight (%)||Benchmark weight (%)" Value="Ab||U||||1.2170000000000||" Date="8/31/2011" />
          <TopHoldingsEntry Type="CName||C||S||Fund Weight (%)||Benchmark weight (%)" Value="Acc||I||||1.2170000000000||" Date="7/31/2011" />

2 个答案:

答案 0 :(得分:2)

您正在考虑sum = sum + value这一事实表明您正在尝试执行此操作,就像使用过程语言一样,通过编写循环并更改变量的值。好吧,XSLT不是一种过程语言,所以你需要以不同的方式思考。

在XSLT 2.0中,这只是

format-number(
   sum(for $x in TopHoldingsEntry/@Type return number(substring-after('||||'))),
   ....)

在XSLT 1.0中,它有点困难。我会使用“兄弟递归”:

<xsl:template match="TopHoldingsEntry">
  <xsl:param name="total" select="0"/>
  <xsl:choose>
    <xsl:when test="following-sibling::*">
      <xsl:apply-templates select="following-sibling::*[1]">
         <xsl:with-param name="total" select="$total + number(substring-after(....))"/>
      </xsl:apply-templates>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$total"/>
    </xsl:otherwise>
  <xsl:choose>
</xsl:template>

然后使用<xsl:apply-templates select="TopHoldingsEntry[1]"/>

关闭此过程

答案 1 :(得分:0)

在格式化数字

之前进行求和
<xsl:variable name="total">
    <xsl:value-of select="number(substring(substring-after(@Value,'||||'),1,10))+
       number(substring(substring-after(@Value,'||||'),1,10))"/>
</xsl:variable>
<xsl:variable name="totalMarks" select="format-number($total,1,10),'#.#')"/>