XSLT 1.0 如何使用 sum() 用逗号对值求和 - 在 xpath 中行走 [英] XSLT 1.0 how to sum values with commas using sum() - walking in xpath

查看:38
本文介绍了XSLT 1.0 如何使用 sum() 用逗号对值求和 - 在 xpath 中行走的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XSLT 1.0 转换要编写,但我没有在网上找到适合我的问题的解决方案.我有以下 XML 示例:

I have an XSLT 1.0 transformation to write and I am not finding online good solutions for my problem. I have the following XML example:

    <?xml version="1.0" encoding="utf-8"?>

    <MainDoc>
    <node1>
            <node2>
                    <User>jsmith</User>
                    <Amount>1,23</Amount>
            </node2>
            <node2>
                    <User>abrown</User>
                    <Amount>4,56</Amount>
            </node2>
    </node1>

如您所见,由于逗号,求和函数不起作用.我需要的是对所有金额值求和,即 1,23 + 4,56 + 等...

As you can see the sum function would not work due to the comma. What I need is to sum all the Amount values, i.e. 1,23 + 4,56 + etc...

我尝试了各种解决方案,但都没有成功.大多数情况下,我找到了基本的例子,但没有像这种情况.

I tried various solutions without any success. Mostly I found basic examples but nothing like this case.

问题是我想要一个从 XSLT 代码调用的转换,例如:

The problem is that I would like a transformation to call from the XSLT code, something like:

    <xsl:call-template name="sumAll">
        <xsl:with-param name="node" select="/MainDoc/node1/node2/Amount"/> 
    </xsl:call-template>

这样,它将对/MainDoc/node1/node2 路径中的Amount"的所有值求和.

So that, it will sum all the value of "Amount" in the /MainDoc/node1/node2 path.

感谢任何帮助

推荐答案

我建议你这样做:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/MainDoc">
    <!-- first-pass -->
    <xsl:variable name="numbers">
        <xsl:for-each select="node1/node2/Amount">
            <num>
                <xsl:value-of select="translate(., ',', '.')"/>
            </num>
        </xsl:for-each>
    </xsl:variable>
    <!-- output -->
    <total>
        <xsl:value-of select="format-number(sum(exsl:node-set($numbers)/num), '0.00')"/>
    </total>
</xsl:template>

</xsl:stylesheet>

应用于您的示例,结果将是:

Applied to your example, the result will be:

<?xml version="1.0" encoding="UTF-8"?>
<total>5.79</total>

请注意,结果使用小数点,而不是小数点逗号.如果需要,您可以通过更改 format-number() 使用的格式来更改此设置.

Note that the result uses a decimal point, not decimal comma. If you want, you can change this by changing the format used by format-number().

这篇关于XSLT 1.0 如何使用 sum() 用逗号对值求和 - 在 xpath 中行走的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆