XSL多输入参数(品牌、分组)联合过滤XML数据的实现方案
XSLT多条件(品牌+分组)过滤实现方案
原有代码问题说明
之前的分组过滤逻辑不生效,核心是两个错误:
- 过滤器放置位置不合理:分组是product的父级节点,在
product_list层先筛分组、再在分组内层筛产品,逻辑更清晰,也不会遍历无效节点 - XPath路径写法错误:在product节点的筛选谓词中,
./代表当前product节点本身,写./group是找product下的子节点group,但实际group是product的父节点,路径完全不匹配
具体修改步骤
1. 修改product_list匹配模板,先做分组维度过滤
在选择分组节点时就加上分组判断,只保留符合选中条件的分组,替换原有模板代码:
<xsl:template match="product_list"> <table class="catalog_table"> <!-- 分组过滤逻辑:选中全部则保留所有分组,否则仅保留name属性匹配选中值的分组 --> <xsl:apply-templates select="group[($selected_group = 'all') or (@name = $selected_group)]"/> </table> </xsl:template>
2. 修改group匹配模板,保留品牌过滤+修正排序逻辑
这一层只需要处理品牌维度的过滤即可,同时修正原来写错的排序规则(原排序写法取的是子节点product,不是当前待排序的product节点的属性),替换原有模板代码:
<xsl:template match="group"> <!-- 可选:加分组表头,不需要可以删除这部分 --> <tr> <th colspan="3"><xsl:value-of select="@name"/></th> </tr> <!-- 品牌过滤:选中全部则保留当前分组下所有产品,否则仅保留品牌匹配的产品 --> <xsl:apply-templates select="product[($selected_brand='all') or (brand = $selected_brand)]"> <xsl:sort select="@id" data-type="text" order="ascending"/> </xsl:apply-templates> </xsl:template>
可选:单层级过滤写法
如果不想分层过滤,想把两个条件都写在product选择逻辑里,需要通过..取父节点的属性,写法参考:
<xsl:template match="group"> <xsl:apply-templates select="product[ (($selected_brand='all') or (brand = $selected_brand)) and (($selected_group='all') or (../@name = $selected_group)) ]"> <xsl:sort select="@id" data-type="text" order="ascending"/> </xsl:apply-templates> </xsl:template>
注意:当前表单里分组下拉框的option值绑定的是分组的
@name属性(比如"Air Pneumatic Parts"),如果想按分组id(比如PN08)筛选,把下拉框option的value="{@name}"改成value="{@id}",同时过滤条件里的@name改成@id即可。
规则验证
修改后完全符合提出的4条筛选要求:
- Brand=All且Group=All:输出全量4条产品记录
- Brand=ABC且Group=All:输出PN080101、PN080102、EL040101共3条记录
- Brand=All且Group=Air Pneumatic Parts(对应PN08分组):输出PN080101、PN080102、PN080103共3条记录
- Brand=ABC且Group=Lamps & Electrical Parts(对应EL04分组):仅输出EL040101记录
内容的提问来源于stack exchange,提问作者Seong Y. H.
相关产品推荐
相关产品推荐

