在xslt 1.0 中取得當前時間
在xsl中怎麼顯示當前時間,可以使用微軟的xsl名稱空間定義(一種是URL名稱空間命名法: ,一種是URN名稱空間命名法: xmlns:msxsl="urn:schemas-microsoft-com:xslt" ),具體程式碼如下,分別建立hello.xsl檔案和hello.xml檔案於同一目錄下,用IE開啟hello.xml即可看到執行結果。
注意:下面的hello.xsl 中實際使用了兩種xsl名稱空間,一種是微軟的 xmlns:msxsl="urn:schemas-microsoft-com:xslt" ,一種是w3組織的 。
hello.xsl :
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:msfunction ="http://www.mycompany.org/ns/function " exclude-result-prefixes="msxsl msfunction">
<msxsl:script implements-prefix=" msfunction " language="javascript">
<![CDATA[
function clock(){
var time = new Date();
var year = time.getFullYear();
var month = time.getMonth() + 1;
var day = time.getDate();
var hours = time.getHours();
var min = time.getMinutes();
var sec = time.getSeconds();
return year + "/" + month + "/" + day + " " + hours + ":" + min + ":" + sec ;
}
]]>
</msxsl:script>
<xsl:template match="/">
<xsl:value-of select="msfunction:clock()"/>
</xsl:template>
</xsl:stylesheet>
hello.xml :
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="text/xsl" href="hello.xsl"?>
<title>Hello, world!</title>
注意 :上面的 xmlns:msxsl="urn:schemas-microsoft-com:xslt" 只能使用urn這樣的命名方法,我嘗試使用 執行結果會報錯:
使用 XSL 樣式表無法檢視 XML 輸入。請更正錯誤然後單擊 重新整理 按鈕,或以後重試。
另外要注意 msxsl:script 不能在xsl:template內部使用,否則也會出現上面相同錯誤。
曾嘗試在xsl:template內部使用
<msxsl:eval language="javascript">clock();</msxsl:eval> 這樣的寫法無法執行出正確結果。
========================my testing ==================================
hello.xsl :
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:msfunction="http://www.mycompany.org/ns/function" exclude-result-prefixes="msxsl msfunction">
<msxsl:script implements-prefix="msfunction" language="javascript">
<![CDATA[
function clock(){
var time = new Date();
var year = time.getFullYear();
var month = time.getMonth() + 1;
var day = time.getDate();
var hours = time.getHours();
var min = time.getMinutes();
var sec = time.getSeconds();
return year + "/" + month + "/" + day + " " + hours + ":" + min + ":" + sec ;
}
]]>
</msxsl:script>
<xsl:template match="FirstPPEntryDate">
<FirstPPEntryDate type="date" format="dd MMMM yyyy hh:mm:ss aa zz">
<xsl:choose>
<xsl:when test="text()!=''">
<xsl:value-of select="text()"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="msfunction:clock()"/>
</xsl:otherwise>
</xsl:choose>
</FirstPPEntryDate>
</xsl:template>
</xsl:stylesheet>
hello.xml:
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="text/xsl" href="hello.xsl"?>
<FirstPPEntryDate type="Date" format="dd MMMM yyyy hh:mm:ss aa zz">22 September 2010 12:06:12 AM SGT</FirstPPEntryDate>