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

如何在XSLT中遍历对象集合并判断特定属性值

解决方案:XSLT中判断集合是否存在特定属性值的项

核心问题分析

你之前的方案无效,是因为XSLT变量是不可变的——一旦赋值就无法修改。遍历集合时每次给ShowInformationSection赋值,本质是创建了多个同名变量,最终生效的是最后一次赋值的结果,而非累积判断是否存在符合条件的项。

针对你的场景的纯XSLT解法

假设你的输入XML结构大致如下(对应List<SelectedFund>和经纪公司信息):

<InvestmentOrder>
  <BrokerNickname>Investment broker</BrokerNickname>
  <SelectedFunds>
    <SelectedFund FundNo="1"/>
    <SelectedFund FundNo="23"/>
  </SelectedFunds>
</InvestmentOrder>

根据你使用的XSLT版本,选择对应的解法:


方案1:XSLT 2.0及以上(推荐,语法更简洁)

利用原生的集合判断能力,直接检查是否存在符合条件的基金项:

<!-- 定义需要匹配的基金编号列表 -->
<xsl:variable name="targetFundNos" select="('1', '75', '76', '82')"/>

<!-- 一次性判断两个条件:经纪公司匹配 + 存在目标基金 -->
<xsl:if test="BrokerNickname = 'Investment broker' 
              and exists(SelectedFunds/SelectedFund[@FundNo = $targetFundNos])">
  <!-- 插入你需要添加的特定文本段 -->
  <div class="info-section">
    此处为针对特定基金的提示内容...
  </div>
</xsl:if>

也可以用some表达式更直观地表达“任一符合”逻辑:

<xsl:if test="BrokerNickname = 'Investment broker' 
              and some $fund in SelectedFunds/SelectedFund satisfies $fund/@FundNo = $targetFundNos">
  <!-- 文本内容 -->
</xsl:if>

方案2:XSLT 1.0(兼容旧环境)

XSLT 1.0没有原生集合操作,可通过count()或xsl:key实现:

方法A:用字符串匹配+计数
<!-- 用空格分隔目标基金编号,避免部分匹配(比如避免把"12"识别为"1") -->
<xsl:variable name="targetFundNos" select="'1 75 76 82'"/>

<xsl:if test="BrokerNickname = 'Investment broker' 
              and count(SelectedFunds/SelectedFund[
                contains(concat(' ', $targetFundNos, ' '), concat(' ', @FundNo, ' '))
              ]) > 0">
  <!-- 文本内容 -->
</xsl:if>
方法B:用xsl:key优化查询(适合大量基金项的场景)
<!-- 提前定义按FundNo索引的键 -->
<xsl:key name="fundByNo" match="SelectedFund" use="@FundNo"/>

<xsl:if test="BrokerNickname = 'Investment broker' 
              and (key('fundByNo','1') or key('fundByNo','75') or key('fundByNo','76') or key('fundByNo','82'))">
  <!-- 文本内容 -->
</xsl:if>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 18:55:20