如何使用XSLT创建模板,基于日期规则生成指定XML元素
XSLT 实现日期比较生成元素的解决方案
核心逻辑
基于transferDate和exerciseDate的日期对比结果,动态生成<Type>元素:
- 若
transferDate早于exerciseDate,生成<Type>Spot</Type> - 若
transferDate等于或晚于exerciseDate,生成<Type>Forward</Type>
完整XSLT代码
假设你的输入XML中,这两个日期字段属于同一个父节点(比如<Deal>),以下是通用的转换模板:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 身份模板:复制所有未被匹配的节点和属性 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 匹配包含日期的父节点,添加Type元素 --> <xsl:template match="Deal"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> <!-- 定义日期变量 --> <xsl:variable name="transferDate" select="transferDate"/> <xsl:variable name="exerciseDate" select="exerciseDate"/> <!-- 判断日期关系生成Type --> <xsl:choose> <xsl:when test="$transferDate < $exerciseDate"> <Type>Spot</Type> </xsl:when> <xsl:otherwise> <Type>Forward</Type> </xsl:otherwise> </xsl:choose> </xsl:copy> </xsl:template> </xsl:stylesheet>
输入输出示例
输入XML示例
<Root> <Deal> <transferDate>2024-03-10</transferDate> <exerciseDate>2024-04-15</exerciseDate> <Amount>10000</Amount> </Deal> <Deal> <transferDate>2024-05-20</transferDate> <exerciseDate>2024-04-15</exerciseDate> <Amount>20000</Amount> </Deal> </Root>
输出XML示例
<Root> <Deal> <transferDate>2024-03-10</transferDate> <exerciseDate>2024-04-15</exerciseDate> <Amount>10000</Amount> <Type>Spot</Type> </Deal> <Deal> <transferDate>2024-05-20</transferDate> <exerciseDate>2024-04-15</exerciseDate> <Amount>20000</Amount> <Type>Forward</Type> </Deal> </Root>
关键说明
- 日期格式要求:确保
transferDate和exerciseDate的格式为YYYY-MM-DD(符合W3C的xs:date标准),这样XSLT 1.0就能直接进行日期大小比较。 - 身份模板作用:保留输入XML中所有原有节点和属性,只添加我们需要的
<Type>元素,避免破坏原有结构。 - 转义字符:XSLT中
<需要转义为<,否则会被解析为标签起始符导致语法错误。
内容的提问来源于stack exchange,提问作者Iamfitz
相关产品推荐
相关产品推荐

