XQuery/數字格式化
外觀
< XQuery
您希望能夠透過指定數字的格式來輕鬆格式化數字。例如,如果您想使用逗號和兩位小數格式化帶有前導美元符號的數字,您將使用以下“格式”
format-number($my-decimal, "$,000.00")
如果輸入數字為1234,則輸出將為$1,234.00
format-number 是 XSLT 1.0 和 XPath 2.0 中的標準函式。它也包含在XQuery 1.1 需求草案中。為了在 eXist 中使用它,我們只需要為 Saxon XSLT format-number() 函式編寫一個包裝器。為此,您需要執行以下操作
- 從http://prdownloads.sourceforge.net/saxon/saxonb9-1-0-2j.zip下載 Saxon9B XSLT 程式的副本
- 解壓縮包並將三個 jar 檔案(saxon9.jar、saxon9-dom.jar 和 saxon9-xpath.jar)複製到 eXist lib/endorsed 資料夾中
- 在 eXist conf.xml 檔案中註釋掉以下行 <transformer class="org.apache.xalan.processor.TransformerFactoryImpl"/>
- 取消註釋三個啟用 Saxon 作為預設 XSLT 的行
- 重新啟動 eXist 伺服器
- 新增一個將包裝簡單 XSLT 的函式。請參閱以下示例程式碼。
我們將建立一個接受兩個引數的 XQuery 函式。一個是十進位制數,另一個是指定格式的字串。我們將這兩個引數都傳遞給一個小型的 XSLT 樣式表。
(: the numeric picture format function from XPath 2.0. To work with eXist we must enable Saxon as the default XSLT engine. See the conf.xml file in the eXist folder for details. :)
declare function local:format-number($n as xs:decimal ,$s as xs:string) as xs:string {
string(transform:transform(
<any/>,
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:template match='/'>
<xsl:value-of select="format-number({$n},'{$s}')"/>
</xsl:template>
</xsl:stylesheet>,
()
))
};
XSLT 1.0 format-number() 函式接受兩個引數。第一個是十進位制數,第二個是表示您期望的輸出圖片的字串。格式字串在 Java 類DecimalFormat 中定義
如果您想要使用逗號分隔的值:local:format-number($my-decimal, ',000')
如果您想要使用前導美元符號:local:format-number($my-decimal, '$,000')
負數的格式在第二個格式字串後面用逗號分隔。
如果您想要負數帶有減號:local:format-number($my-decimal, '0,000.00;-0,000.00')
Minollo 在他的部落格中釋出了一個 XQuery 函式。他的程式碼通過了一套測試。
我們真誠地希望 XQuery 的未來版本包含允許開發人員輕鬆格式化數字和日期格式的函式。