XSLT格式 - 数字函数不格式化

时间:2012-07-24 12:34:04

标签: xslt numbers format

我需要将值格式化为特定格式,但它看起来并不像是受支持的。

我想用:

format-number($value, '####,##,##,##0')

但尝试此操作时返回的值为'###,###,##0'

因此,如果我$value = '123456789'我希望将值输出为1,24,56,789,但我得到123,456,789

您可以使用哪种格式限制?

如果您转到W3schools并输入以下xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <company>Columbia</company>
        <price>123456789</price>
        <year>1985</year>
    </cd>
    <cd>
        <title>Hide your heart</title>
        <artist>Bonnie Tyler</artist>
        <country>UK</country>
        <company>CBS Records</company>
        <price>123456789</price>
        <year>1988</year>
    </cd>

</catalog>

然后是以下xsl:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<xsl:variable name="TestFormat" select="'###,##,##,##0'"/>
  <html>
  <body>
  <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th>Title</th>
        <th>Artist</th>
      </tr>
      <xsl:for-each select="catalog/cd">
      <tr>
        <td><xsl:value-of select="title"/></td>
        <td><xsl:value-of select="format-number(price, $TestFormat)"/></td>
      </tr>
      </xsl:for-each>
    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

你可以看到我没有得到所需的格式。有什么建议吗?

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

分组分隔符,仅在小数点分隔符后面的第一次出现时被尊重。这是因为W3C specifies 格式模式字符串是由JDK 1.1 DecimalFormat类指定的语法。 Looking at that class显示它具有整数分组大小属性,因此变量组整个格式的大小不能由该类建模。

因此,在编写###,##,##,##0时,分组大小设置为3(最右边的分组分隔符,与格式字符串末尾之间的位数,以及写入###,##,##,0时,每个数字之间会有一个分组分隔符。

如果真的,想要在没有任何外部格式化工具/函数的情况下在XSLT中执行此操作,您可以使用string-lengthconcatsubstring功能并手动插入组分隔符。

更新:这些语句仅对XSLT 1.0有效。

答案 1 :(得分:1)

对于8和9个字符串,以下内容可以使用:

      <td>
        <xsl:value-of select="substring(price,1,1)"/>
        <xsl:text>,</xsl:text>
        <xsl:value-of select="substring(price,2,1)"/>
        <xsl:value-of select="substring(price,4,1)"/>
        <xsl:text>,</xsl:text>
        <xsl:value-of select="substring(price,5,2)"/>
        <xsl:text>,</xsl:text>
        <xsl:value-of select="substring(price,7,3)"/>
        <xsl:if test="string-length(price) &lt; 9">
          <xsl:value-of select="0"/>
        </xsl:if>
      </td>

根据您的意图,可能需要移动或更改“if”块以完成稍微不同的格式化。

答案 2 :(得分:1)

现在是你搬到XSLT 2.0的时候了。随着Saxon的当前版本,您的代码会生成此输出:

<html>
   <body>
      <h2>My CD Collection</h2>
      <table border="1">
         <tr bgcolor="#9acd32">
            <th>Title</th>
            <th>Artist</th>
         </tr>
         <tr>
            <td>Empire Burlesque</td>
            <td>12,34,56,789</td>
         </tr>
         <tr>
            <td>Hide your heart</td>
            <td>12,34,56,789</td>
         </tr>
      </table>
   </body>
</html>
相关问题