技术问询:使用XSLT按日期字段升序转换JSON数据
XSLT实现按transactionEffectiveDate升序排序JSON的方案
Hey Mike, here's a practical XSLT solution to sort your transaction list by the transactionEffectiveDate field in ascending order. This works with XSLT 3.0+ (supported by processors like Saxon-HE):
完整XSLT代码
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" encoding="UTF-8"/> <xsl:template match="/"> <!-- 把输入JSON转成XML结构,方便XSLT处理 --> <xsl:variable name="xmlData" select="json-to-xml(.)"/> <!-- 构建排序后的XML结构,后续转回JSON --> <xsl:variable name="sortedXml"> <map xmlns="http://www.w3.org/2005/xpath-functions"> <array key="transactions"> <!-- 对transaction元素按transactionEffectiveDate升序排序 --> <xsl:for-each select="$xmlData//array[@key='transactions']/map"> <xsl:sort select="string(data[@key='transactionEffectiveDate'])" order="ascending" data-type="text"/> <xsl:copy-of select="."/> </xsl:for-each> </array> </map> </xsl:variable> <!-- 将排序后的XML转换回带缩进的JSON --> <xsl:value-of select="xml-to-json($sortedXml, map{'indent': true()})"/> </xsl:template> </xsl:stylesheet>
关键逻辑解释
json-to-xml():XSLT 3.0原生函数,把输入JSON转换成标准XML结构(遵循http://www.w3.org/2005/xpath-functions命名空间),让我们能利用XSLT的排序能力处理数据。<xsl:sort>:因为你的日期是YYYY-MM-DD格式,直接按文本值升序排序就和实际日期顺序完全一致,不需要额外做日期类型转换,简单高效。xml-to-json():把排序后的XML转回JSON,map{'indent': true()}参数让输出的JSON带缩进,可读性更强。
使用提示
只要把这段XSLT和你的输入JSON一起交给支持XSLT 3.0的处理器运行,就能得到按transactionEffectiveDate升序排列的JSON结果啦。
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

