You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XSLT apply-templates节点筛选失效求助:条件未正确过滤节点

问题排查与修正方案

错误原因

你当前的代码逻辑存在两个关键问题:

  • employeeList[employee/dep = '7']这个表达式是判断整个employeeList节点是否包含至少一个dep=7的employee,只要满足该条件,就会选中整个employeeList节点,而非筛选其中符合条件的employee。
  • 模板内的<xsl:for-each select="employee">会遍历该employeeList下的所有employee节点,自然会包含dep=9的条目,导致过滤失效。

修正方案(基础需求:筛选dep=7的employee)

有两种简洁的修正方式:

方式1:直接筛选目标employee节点

调整apply-templates的选择范围,直接定位到符合条件的employee,再用模板处理单个employee:

<xsl:apply-templates select="employeeList/employee[dep = '7']" mode="e"/>

<xsl:template match="employee" mode="e">
    <dep>
        <xsl:value-of select="dep"/>
    </dep>
</xsl:template>

方式2:在for-each中添加过滤条件

如果仍需匹配employeeList节点,只需在for-each的select表达式中增加过滤条件:

<xsl:apply-templates select="employeeList" mode="e"/>

<xsl:template match="employeeList" mode="e">
    <xsl:for-each select="employee[dep = '7']">
        <dep>
            <xsl:value-of select="dep"/>
        </dep>
    </xsl:for-each>
</xsl:template>

扩展到最终需求:筛选dep=7且无city标签的employee

只需把过滤条件修改为employee[dep = '7' and not(city)]即可,示例代码:

<xsl:apply-templates select="employeeList/employee[dep = '7' and not(city)]" mode="e"/>

<xsl:template match="employee" mode="e">
    <dep>
        <xsl:value-of select="dep"/>
    </dep>
    <salary>
        <xsl:value-of select="salary"/>
    </salary>
</xsl:template>

这样处理后,输出会只包含dep=7且没有city节点的employee数据,符合你的预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:50:44