如何用XSLT 1.0或XQuery生成含动态时间的SOAP安全头
动态生成SOAP安全头:XSLT 1.0与XQuery实现方案
XSLT 1.0 实现方式
XSLT 1.0本身没有原生的日期时间处理函数,要生成符合要求的UTC时间戳,主要有两种可行方案:
- 依赖处理器扩展函数:主流XSLT处理器(如Saxon、Xalan)提供了扩展函数来处理日期时间。比如用EXSLT的
exslt:date-time()获取当前UTC时间,再通过处理器扩展函数增加1分钟:
注意:扩展函数依赖具体处理器,跨环境使用需对应调整。<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exslt="http://exslt.org/dates-and-times" xmlns:saxon="http://saxon.sf.net/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" exclude-result-prefixes="exslt saxon"> <xsl:template match="/"> <soapenv:Header> <wsse:Security soapenv:mustUnderstand="1"> <wsu:Timestamp wsu:Id="TS-{generate-id()}"> <wsu:Created> <xsl:value-of select="exslt:date-time()"/> </wsu:Created> <wsu:Expires> <!-- 为当前时间增加60秒(1分钟) --> <xsl:value-of select="saxon:add(exslt:date-time(), 'PT60S')"/> </wsu:Expires> </wsu:Timestamp> </wsse:Security> </soapenv:Header> </xsl:template> </xsl:stylesheet> - 手动拼接时间字符串:若无法使用扩展函数,只能通过字符串拼接生成时间,但精度和准确性难以保障,不推荐。
XQuery 实现方式
XQuery 1.0及以上版本具备原生日期时间处理函数,可直接实现需求:
declare namespace soapenv = "http://schemas.xmlsoap.org/soap/envelope/"; declare namespace wsse = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; declare namespace wsu = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"; let $current-time := current-dateTime() let $expires-time := $current-time + xs:dayTimeDuration("PT60S") return <soapenv:Header> <wsse:Security soapenv:mustUnderstand="1"> <wsu:Timestamp wsu:Id="TS-{fn:generate-id()}"> <wsu:Created>{$current-time}</wsu:Created> <wsu:Expires>{$expires-time}</wsu:Expires> </wsu:Timestamp> </wsse:Security> </soapenv:Header>
current-dateTime()用于获取当前UTC时间,xs:dayTimeDuration("PT60S")定义60秒的时长,两者直接相加即可得到晚1分钟的时间,输出格式完全符合ISO 8601标准。
内容的提问来源于stack exchange,提问作者Simran
相关产品推荐
相关产品推荐

