在XQuery / XSLT / XPath中格式化sum()函数的输出

时间:2011-05-04 17:58:36

标签: xml xslt xpath xquery

我有一个关于在XQuery / XSLT / XPath中格式化sum()函数输出的问题。我有一个XSLT样式表和一个XQuery。我能够在XSLT中获得正确的格式,但不能在XQuery中获得。

以下是输入文件的示例:

<userTotals>
  <user cost="138764.63" hours="1506.51"/>
  <user cost="329555.76" hours="3577.85"/>
  <user cost="213909.81" hours="2322.33"/>
  <user cost="22684.85" hours="246.28"/>
  <user cost="6147.42" hours="66.74"/>
  <user cost="1269.27" hours="13.78"/>
  <user cost="181.45" hours="1.97"/>
  <user cost="755.30" hours="8.2"/>
</userTotals>

以下是样式表示例:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/userTotals">
    <results>
      <cost><xsl:value-of select="sum(user/@cost)"/></cost>
      <hours><xsl:value-of select="sum(user/@hours)"/></hours>
      <hours-formatted>
        <xsl:value-of select="format-number(sum(user/@hours),'###.##')"/>
      </hours-formatted>
    </results>
  </xsl:template>

</xsl:stylesheet>

这是输出:

<results>
   <cost>713268.49</cost>
   <hours>7743.659999999999</hours>
   <hours-formatted>7743.66</hours-formatted>
</results>

注意<hours><hours-formatted>的输出。 <hours>的内容是sum()的未修改/未格式化输出。 <hours-formatted>的内容是我希望在XSLT和XQuery中格式化数字的方式。

问题是在XQuery中,format-number()不可用。如何在XSLT和XQuery中以相同的方式格式化sum()的结果,以便结果显示为<hours-formatted>

我是否需要创建一个将sum()的输出作为字符串并自己处理小数的函数?在这种情况下,我需要将.659舍入到.66。我希望有更好的方法来做到这一点(可能将结果转换为不同的类型然后??)。

感谢您提供的任何信息/指导。

2 个答案:

答案 0 :(得分:3)

Saxon-PE及以上版本在XQuery中提供format-number()作为扩展函数(或通过启用XQuery 3.0支持)。

但你可以使用round-half-to-even()函数实现你想要的效果。

答案 1 :(得分:1)

这个XQuery表达式:

let $sum := string(ceiling(sum(/*/user/@hours) * 100)),
    $length := string-length($sum)
return
  concat(
     substring($sum, 1, $length - 2),
     '.',
     substring($sum, $length - 1)
  )

输出:

7743.66
相关问题