[英]XPath format-number with number of decimal places based on a variable?
我有一个XML文档,其中应报告特定xs:decimal
保留在同级节点中。 我目前正在努力寻找一种通过format-number
函数输出此结果的简单方法。
我可以使用其他一些函数构建图片字符串,但是对于应该(至少是imo)一项相对直接且常见的任务来说,这似乎非常困难。
例如,我目前正在做的事情是这样的:
<xsl:value-of
select="format-number(myNode/DecimalValue,
concat('#0.',
string-join(for $i in 1 to myNode/DecimalPlaces return '0'))"
/>
有没有更好的办法?
很好的问题! 这通常意味着,我不知道答案,但我希望其他人也这样做,因为这对我来说也很痛苦。
无论如何,我进行了一些搜索,我认为round-half-to-even
功能可能会解决问题( http://www.xqueryfunctions.com/xq/fn_round-half-to-even.html )
您的代码将变为:
<xsl:value-of
select="
round-half-to-even(
myNode/DecimalValue
, myNode/DecimalPlaces
)
"
/>
现在切线:对于使用XSLT 1.1或更低版本以及XPath 1的用户,可以使用以下方法:
<xsl:value-of
select="
concat(
substring-before(DecimalValue, '.')
, '.'
, substring(substring-after(DecimalValue, '.'), 1, DecimalPlaces -1)
, round(
concat(
substring(substring-after(DecimalValue, '.'), DecimalPlaces, 1)
, '.'
, substring(substring-after(DecimalValue, '.'), DecimalPlaces+1)
)
)
)
"
/>
当然,此代码比原始代码差 ,但是如果有人知道如何解决XPath 1的原始问题,并且比这个想法更好,我很乐意听到。 (我希望世界越来越多地完全跳过XML并立即转移到JSON)
<!-- use a generous amount of zeros in a top-level variable -->
<xsl:variable name="zeros" select="'000000000000000000000000000000000'" />
<!-- …time passes… -->
<xsl:value-of select="
format-number(
myNode/DecimalValue,
concat('#0.', substring($zeros, 1, myNode/DecimalPlaces))
)
" />
您可以将其抽象为模板:
<!-- template mode is merely to prevent collisions with other templates -->
<xsl:template match="myNode" mode="FormatValue">
<xsl:value-of select="
format-number(
DecimalValue,
concat('#0.', substring($zeros, 1, DecimalPlaces))
)
" />
</xsl:template>
<!-- call like this -->
<xsl:apply-templates select="myNode" mode="FormatValue" />
您还可以制作一个命名模板,并在调用它时使用XSLT上下文节点。 如果可行,则取决于您的输入文档和需求。
<xsl:template name="FormatValue">
<!-- same as above -->
</xsl:template>
<!-- call like this -->
<xsl:for-each select="myNode">
<xsl:call-template name="FormatValue" />
</xsl:for-each>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.