在XSLT中用逗号作为小数点分隔符求和数字? [英] Summing numbers with comma as decimal separator in XSLT?
问题描述
我有一个 XML 文件,其中的数字以逗号分隔
I have an XML file where the number are comma-separated
<foo>
<bar val="1,23"/>
<bar val="4,56"/>
<bar val="7,89"/>
</foo>
我想对 XSLT 中的 /foo/bar/@val
值求和,但我对格式有点卡住了.有谁知道正确的语法是什么?
I would like to make a sum over /foo/bar/@val
values in XSLT, but I am a bit stuck the formatting. Does anyone knows what would be the proper syntax?
推荐答案
我猜,在 "val"
属性中指定的值是一个带有逗号而不是小数点的数字.
I am guessing, that the value specified in a "val"
attribute is a number that has comma instead of a decimal point.
可能有多种解决方案:
我.XSLT 1.0
这种转变:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="http://exslt.org/common"
>
<xsl:output method="text"/>
<!-- -->
<xsl:template match="foo">
<xsl:variable name="vrtfBars">
<xsl:for-each select="bar">
<bar val="{translate(@val, ',', '.')}"/>
</xsl:for-each>
</xsl:variable>
<!-- -->
<xsl:value-of select=
"sum(ext:node-set($vrtfBars)/*/@val)"/>
</xsl:template>
</xsl:stylesheet>
应用于最初提供的 XML 文档时:
<foo>
<bar val="1,23"/>
<bar val="4,56"/>
<bar val="7,89"/>
</foo>
产生想要的结果:
13.68
二.XSLT 2.0
这种转变:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="f xs"
>
<xsl:output method="text"/>
<!-- -->
<xsl:template match="foo">
<xsl:sequence select=
"sum(bar/@val/number(translate(., ',', '.')))"
/>
</xsl:template>
</xsl:stylesheet>
应用于同一个 XML 文档时,产生相同的正确结果:
13.68
三.FXSL 2.x
这种转变:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:f="http://fxsl.sf.net/"
xmlns:my="my:fun"
exclude-result-prefixes="my f xs"
>
<xsl:import href="../f/func-transform-and-sum.xsl"/>
<!-- -->
<xsl:output method="text"/>
<!-- -->
<xsl:template match="foo">
<xsl:sequence select=
"sum(
f:transform-and-sum(my:makeNum(), bar/@val )
)"
/>
</xsl:template>
<!-- -->
<xsl:function name="my:makeNum" as="xs:double">
<xsl:param name="psNum" as="xs:string"/>
<!-- -->
<xsl:sequence select="number(translate($psNum, ',', '.'))"/>
</xsl:function>
<!-- -->
<xsl:function name="my:makeNum" as="element()">
<my:makeNum/>
</xsl:function>
<!-- -->
<xsl:template match="my:makeNum" as="xs:double" mode="f:FXSL">
<xsl:param name="arg1" as="xs:string"/>
<!-- -->
<xsl:sequence select="my:makeNum($arg1)"/>
</xsl:template>
</xsl:stylesheet>
当应用于同一个 XML 文档时会产生相同的正确结果:
13.68
最后一种解决方案更加灵活,并且可以在求和之前需要对值进行更复杂的转换时成功使用.
The last solution is more flexible and can be used successfully when a more complex transformation of the values is needed before summing.
这篇关于在XSLT中用逗号作为小数点分隔符求和数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!