BloggerAds

2011年5月22日 星期日

XSL中轉換產出格式的方法

使用XSL來轉XML時,若要在XSL中轉換產出值的格式,有下列幾種方式:
一、可使用一些內建的函式來做轉換 (但內建的函式實在是很少...):
<x:value-of select="format-number([節點名稱], '###,###')"/>
則會將數字的資料轉為如 123,456 這種格式

二、自已寫XSL的function來做轉換

三、寫Script來做轉換,這個方式可以做到的功能就很多了,看是要用JavaScript、C#、VB...都可以,下列的例子是用來做日期轉換的函式:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl [前置詞]" extension-element-prefixes="msxsl" xmlns:[前置詞]="urn:[前置詞]">

若是用Visual Studio 2008產生的XSL檔案的話,要在上面這段加入下面兩段文字
1. xmlns:[前置詞]="urn:[前置詞]"
2. exclude-result-prefixes="msxsl [前置詞]"

[前置詞] 是由自已隨便輸入的,但在使用時要注意全部都要相同。接下來再加入下列程式碼(範例):
<msxsl:script implements-prefix="[前置詞 ]" language="C#">
    <![CDATA[
      public string FormatDateTime(string xsdDateTime, string format) {
          DateTime date = DateTime.Parse(xsdDateTime);
          return date.ToString(format);
      }
    ]]>
</msxsl:script>

最後在使用時,直接像下面程式般呼叫函式,即可做到相當多的功能。
<xsl:value-of select="[前置詞 ]:FormatDateTime([節點名稱], 'yyyy MM DD')"/>

參考:
http://stackoverflow.com/questions/500915/format-a-date-in-xml-via-xslt
http://stackoverflow.com/questions/669291/xslt-decimal-formatting-based-on-input-xml
http://www.w3schools.com/xsl/

沒有留言:

張貼留言