XSL转换的数字总和

时间:2014-10-17 14:14:26

标签: xml xslt sum

我想计算余额客户的总和。

这是我的XML代码:
<bank> <accounts> <deposit-accounts> <deposit-account id="d1" interesse="0.03"> <balance>2500</balance> </deposit-account> <deposit-account id="d2" interesse="0.03"> <balance>15075</balance> </deposit-account> </deposit-accounts> <bank-accounts> <bank-account id="c1"> <balance>4025</balance> </bank-account> <bank-account id="c2"> <balance>-125</balance> </bank-account> <bank-account id="c3"> <balance>325</balance> </bank-account> </bank-accounts> </accounts> <customers> <customer> <name>Ben Richerdson</name> <address>Park Drive 2</address> <accounts> <bank-account ref="c2" /> <deposit-account ref="d1" /> <bank-account ref="c1" /> </accounts> </customer> </customers> </bank> 这是我的XSL代码:     <xsl:for-each select="customer">
<xsl:for-each select="accounts/*"> <xsl:variable name="account" select="@ref" /> <xsl:for-each select="/bank/accounts/bank-accounts/bank-account"> <xsl:if test="@id = $account"> <xsl:value-of select="@id" /> <xsl:value-of select="balance" /> </xsl:if> </xsl:for-each> <xsl:for-each select="/bank/accounts/deposit-accounts/deposit-account"> <xsl:if test="@id = $account"> <xsl:value-of select="@id" /> <xsl:value-of select="balance" /> </xsl:if> </xsl:for-each> </xsl:for-each> </xsl:for-each>

最后,我想计算客户账户余额的总和。 在这种情况下,我希望客户&#34; Ben Richerdson&#34;的结果为-125 + 4025 + 2500 = 6400。 我尝试使用sum函数,但结果是-12540252500(即字符串的连接) 你能帮助我吗? 非常感谢

1 个答案:

答案 0 :(得分:0)

定义一个键

<xsl:key name="ac" match="bank/accounts/deposit-accounts/deposit-account | bank/accounts/bank-accounts/bank-account" use="@id"/>

然后你可以写

<xsl:template match="customer">
  <xsl:value-of select="sum(key('ac', accounts/*/@ref)/balance)"/>
</xsl:template>

以下是完整的示例:

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

<xsl:key name="ac" match="bank/accounts/deposit-accounts/deposit-account | bank/accounts/bank-accounts/bank-account" use="@id"/>

<xsl:template match="/">
  <xsl:apply-templates select="//customer"/>
</xsl:template>

<xsl:template match="customer">
  Name: <xsl:value-of select="name"/>, sum:<xsl:value-of select="sum(key('ac', accounts/*/@ref)/balance)"/>
</xsl:template>

</xsl:stylesheet>

当我使用Saxon 6.5.5针对您的输入样本运行时,它会输出Name: Ben Richerdson, sum:6400