如何在XSLT 3.0中获取当前时间戳分量并生成指定格式XML节点
XSLT获取当前时间生成指定时间节点的实现方法
实现逻辑根据你使用的XSLT版本不同,分为两种方案:
XSLT 2.0/3.0 原生实现(无依赖)
XSLT 2.0开始内置了完整的日期时间处理函数,直接调用current-dateTime()就能获取当前时间戳,再通过内置的分量提取函数拆分即可,不需要任何扩展支持:
<DateTimeOrdered> <Year><xsl:value-of select="year-from-dateTime(current-dateTime())"/></Year> <Month><xsl:value-of select="month-from-dateTime(current-dateTime())"/></Month> <Day><xsl:value-of select="day-from-dateTime(current-dateTime())"/></Day> <Hour24><xsl:value-of select="hours-from-dateTime(current-dateTime())"/></Hour24> <Minute><xsl:value-of select="minutes-from-dateTime(current-dateTime())"/></Minute> <Second><xsl:value-of select="floor(seconds-from-dateTime(current-dateTime()))"/></Second> <MilliSeconds><xsl:value-of select="floor((seconds-from-dateTime(current-dateTime()) - floor(seconds-from-dateTime(current-dateTime()))) * 1000)"/></MilliSeconds> </DateTimeOrdered>
如果是XSLT 3.0环境,还可以用format-dateTime()函数简化写法,直接通过格式占位符提取各时间分量。
XSLT 1.0 兼容实现
XSLT 1.0没有内置获取系统时间的函数,需要结合扩展或者传参实现:
- 优先推荐方案:如果你的后端是C#技术栈,直接在C#调用XSLT的代码里先获取
DateTime.Now,封装成XSLT参数传入转换上下文,在XSLT里直接读取参数拆分即可,完全没有兼容问题,也不会有扩展函数的权限限制,稳定性最高。 - 如果需要在XSLT内部直接获取,绝大多数主流XSLT 1.0处理器(Xalan、libxslt、.NET平台处理器等)都支持EXSLT扩展库的日期函数,先在样式表根节点声明日期扩展命名空间,拿到ISO格式时间字符串后做字符串截取即可:
<!-- 根节点声明扩展命名空间 --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:date="http://exslt.org/dates-and-times" extension-element-prefixes="date"> <!-- 其余样式表内容 --> <xsl:variable name="currentTime" select="date:date-time()"/> <DateTimeOrdered> <Year><xsl:value-of select="substring($currentTime,1,4)"/></Year> <Month><xsl:value-of select="number(substring($currentTime,6,2))"/></Month> <Day><xsl:value-of select="number(substring($currentTime,9,2))"/></Day> <Hour24><xsl:value-of select="number(substring($currentTime,12,2))"/></Hour24> <Minute><xsl:value-of select="number(substring($currentTime,15,2))"/></Minute> <Second><xsl:value-of select="number(substring($currentTime,18,2))"/></Second> <MilliSeconds><xsl:value-of select="number(substring($currentTime,21,3))"/></MilliSeconds> </DateTimeOrdered>
注意:EXSLT返回的时间格式为标准ISO 8601格式(如
2022-06-03T07:07:07.150+08:00),截取位置固定,只要处理器支持该扩展就能稳定运行。
内容的提问来源于stack exchange,提问作者Manish Partey
相关产品推荐
相关产品推荐

