如何用XSLT筛选保留EventType不等于HardBounce的XML节点
问题排查
- 你的XSLT逻辑核心错误出在判断条件的路径使用上:
xsl:if里的/root/Interaction/EventType/text()是全局绝对路径,会匹配文档中所有Interaction节点的EventType值,无法针对当前正在处理的单个Interaction做判断。 - 额外冗余点:你已经定义了全局的复制模板,不需要在
Interaction的匹配模板里重复写复制逻辑,直接过滤掉不需要的节点即可。
正确实现方案
方案1:基于你现有代码修改
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="3.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> <xsl:template match="/root/Interaction"> <!-- 这里用相对路径,判断当前Interaction的EventType值 --> <xsl:if test="EventType != 'HardBounce'"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:if> </xsl:template> </xsl:stylesheet>
方案2:更简洁的空模板过滤写法(推荐)
直接匹配需要排除的节点,不需要写if判断,逻辑更清晰:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="3.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> <!-- 匹配EventType为HardBounce的Interaction节点,直接不输出任何内容 --> <xsl:template match="Interaction[EventType = 'HardBounce']"/> </xsl:stylesheet>
两种方案运行后都会输出你预期的结果。
内容的提问来源于stack exchange,提问作者shibu
相关产品推荐
相关产品推荐

