我试图打印总和,但它打印每个值的总和。我想得到总金额。如何在 xsl 中使用全局变量
作为获取总和的示例,简单地我们可以写sum = sum + value;
值是我们得到的新值,总和已经是现有值。 我注意到的是它总是在XSL中被覆盖。
这是我使用的代码
<xsl:template match="Top">
<xsl:if test="position() <= 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" />
您正在考虑 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]"/>
启动该过程
在格式化数字之前求和
<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),'#.#')"/>