如何通过XSLT1向XML文件添加日期时间
XSLT 1.0 添加当前日期时间的解决方案
XSLT 1.0本身没有内置的日期时间函数,你可以通过以下几种可行方案实现需求:
方法1:使用EXSLT扩展函数(多数处理器支持)
很多XSLT 1.0处理器(比如Saxon、libxslt)支持EXSLT的日期扩展,只需添加对应命名空间,调用date:date-time()即可获取ISO格式的当前日期时间。
修改后的XSLT代码:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:date="http://exslt.org/dates-and-times" exclude-result-prefixes="date" version="1.0"> <xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="resultset"> <products> <timestamp><xsl:value-of select="date:date-time()"/></timestamp> <xsl:apply-templates/> </products> </xsl:template> </xsl:stylesheet>
方法2:针对微软MSXSL处理器的脚本扩展
如果你使用的是微软的msxsl.exe处理器,可以通过内嵌脚本直接获取系统时间:
修改后的XSLT代码:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:custom="urn:custom-functions" exclude-result-prefixes="msxsl custom" version="1.0"> <xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <msxsl:script language="JScript" implements-prefix="custom"> function getDateTime() { return new Date().toISOString(); } </msxsl:script> <xsl:template match="resultset"> <products> <timestamp><xsl:value-of select="custom:getDateTime()"/></timestamp> <xsl:apply-templates/> </products> </xsl:template> </xsl:stylesheet>
方法3:从外部传递日期时间参数
如果你的XSLT处理器支持传递参数(比如命令行调用时传入),可以在调用时把当前日期时间作为参数传入,这种方式兼容性最好:
XSLT代码修改:
<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output indent="yes"/> <xsl:strip-space elements="*"/> <!-- 定义接收参数 --> <xsl:param name="currentDateTime"/> <xsl:template match="resultset"> <products> <timestamp><xsl:value-of select="$currentDateTime"/></timestamp> <xsl:apply-templates/> </products> </xsl:template> </xsl:stylesheet>
调用示例(以msxsl为例):
命令行执行时传入参数:
msxsl.exe input.xml your-stylesheet.xsl currentDateTime="2024-05-20T15:30:00Z"
其他处理器(比如Saxon)也有类似的参数传递方式,可根据对应文档调整。
内容的提问来源于stack exchange,提问作者user3358102
相关产品推荐
相关产品推荐

