You need to enable JavaScript to run this app. XSLT 结合Unit关联与日期规则过滤删除指定XML节点
优惠活动
大模型
产品
解决方案
定价
更多

XSLT 结合Unit关联与日期规则过滤删除指定XML节点

原XSLT规则失效的核心原因
  • 版本不兼容:原代码声明XSLT版本为1.0,但使用了仅XSLT 2.0及以上支持的current-date()函数、日期类型自动转换能力,在1.0解析器中运行会直接报错,匹配规则完全不生效。
  • 类型不匹配:测试XML中的StartDate、EndDate是带时分秒毫秒后缀的格式字符串(如2021-01-01T00:00:00.000),即使在2.0环境下,直接和纯日期类型的current-date()比较会触发类型不匹配,无法得到正确的判断结果。
  • 非法值无容错:测试样例XML中存在2021-02-31、2021-01-093这类不符合ISO 8601格式的非法日期字符串,直接做类型转换会导致解析异常,中断整个转换流程。
修正后的可运行实现

适配XSLT 2.0+环境(匹配原有写法的修正版)

修正了版本声明、日期类型转换、非法值容错逻辑,可直接运行:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
                xmlns:xs="http://www.w3.org/2001/XMLSchema"
                exclude-result-prefixes="xs"
                version="2.0">  
  <xsl:output method="xml" indent="yes"/>  
  <xsl:strip-space elements="*"/>  

  <!-- 通用节点复制模板,保留所有未命中删除规则的节点原结构 -->
  <xsl:template match="@*|node()"> 
    <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
  </xsl:template>  

  <!-- 命中删除条件的Items节点匹配空模板,触发即不输出 -->
  <xsl:template match="Items[
    <!-- 条件1:Unit字段值为6000 -->
    Unit = '6000'
    <!-- 条件2:当前节点的StartDate 与同层级所有Unit=5000的节点StartDate 无重复 -->
    and not(
      xs:date(StartDate) = ../Items[Unit='5000']/xs:date(StartDate)
    )
    <!-- 条件3:StartDate <= 当前日期 且 EndDate >= 当前日期,加入非法日期容错 -->
    and (try { xs:date(StartDate) } catch * { false() } <= current-date())
    and (try { xs:date(EndDate) } catch * { false() } >= current-date())
  ]"/>
</xsl:stylesheet>

适配XSLT 1.0环境的版本

由于1.0版本不支持内置当前日期函数、日期类型,需要在调用转换时传入格式为YYYY-MM-DD的当前日期参数(和XML中日期前10位格式保持一致),代码如下:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">  
  <xsl:output method="xml" indent="yes"/>  
  <xsl:strip-space elements="*"/>  
  <!-- 外部传入的当前日期参数,格式为YYYY-MM-DD -->
  <xsl:param name="currentDate"/>

  <xsl:template match="@*|node()"> 
    <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
  </xsl:template>  

  <xsl:template match="Items[
    Unit = '6000'
    and not(
      substring(StartDate, 1, 10) = ../Items[Unit='5000']/substring(StartDate, 1, 10)
    )
    and substring(StartDate, 1, 10) <= $currentDate
    and substring(EndDate, 1, 10) >= $currentDate
  ]"/>
</xsl:stylesheet>

原代码中../Items[Unit=5000]/StartDate的路径逻辑是正确的,可正确获取同层级下所有Unit为5000的节点的StartDate值,这部分不需要调整。

内容的提问来源于stack exchange,提问作者SunnyR8394

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.30 12:45:02