XSLT如何基于条件使用for-each实现指定内容筛选
原代码核心问题
- 测试条件语法错误:
contains($Author ='Bero')属于完全错误的XPath写法,一方面将布尔等式判断的结果作为contains()函数的输入,另一方面从未定义过$Author变量,也未读取当前遍历节点的name属性值,条件永远无法正确命中 - 逻辑输出缺失:两个分支内定义的同名
$Store变量仅在当前代码块作用域内有效,定义完成后未做任何节点输出操作,即使逻辑正确也不会产生任何可见结果;同时路径中引用了不存在的u子节点,永远匹配不到有效内容 - 判断逻辑错位:没有按照需求提前校验Author节点的属性特征,反而在逐节点遍历过程中做无意义的嵌套判断,路径指向完全不符合需求设定
修正后可匹配两类测试场景的XSLT代码
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <!-- 保留原代码中内嵌的Bookstore结构 --> <xsl:variable name="Store"> <Bookstore> <Author name="Bero"> <topic>Athletics</topic> </Author> <Author name="ABC"> <topic>Sports</topic> </Author> </Bookstore> </xsl:variable> <xsl:variable name="allAuthorNodes" select="$Store/Bookstore/Author"/> <xsl:choose> <!-- 命中Bero条件:仅输出Bero对应的topic,匹配第一类测试场景预期 --> <xsl:when test="$allAuthorNodes[@name='Bero']"> <xsl:copy-of select="$allAuthorNodes[@name='Bero']/topic"/> </xsl:when> <!-- 命中Aurora条件:输出所有Author下的topic,匹配第二类测试场景预期 --> <xsl:when test="$allAuthorNodes[@name='Aurora']"> <xsl:copy-of select="$allAuthorNodes/topic"/> </xsl:when> </xsl:choose> </xsl:template> </xsl:stylesheet>
代码匹配效果说明
- 第一类测试场景(存在
name="Bero"的Author节点):仅输出<topic>Athletics</topic>,与预期完全一致 - 第二类测试场景(存在
name="Aurora"的Author节点):遍历输出所有Author节点下的topic,即同时输出Athletics、Sports两个topic节点,与预期完全一致
内容的提问来源于stack exchange,提问作者DPUser
相关产品推荐
相关产品推荐

