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

XSLT条件判断问题:如何为目标XML实现if-else/choose-when逻辑

解决XSLT条件处理cd元素nominee属性的问题

需求逻辑

遍历XML中的每个<cd>元素,对其nominee属性执行以下判断:

  • 若属性值以“1 2”开头,直接输出该属性值
  • 否则,将“1 2”与属性值拼接后输出

给定XML代码

<catalog>
<cd nominee ="1 2 First">
    <title company="Grammy" price="10.20">1999 Grammy Nominees</title>
    <artist all="type">Many</artist>
    <country>USA</country>
</cd>
<cd nominee ="Second">
    <title company="Grammy" price="20.20">Grammy Nominees</title>
    <artist all="type">Many</artist>
    <country>UK</country>
</cd>
</catalog>

原代码的错误点

  1. 属性名匹配错误:原XSLT中使用@value,但XML目标属性实际是nominee
  2. 节点上下文错误:starts-with(., '1 2')中的.指向<catalog>节点,而非<cd>的nominee属性,导致判断逻辑完全失效
  3. 遍历逻辑缺失:模板仅匹配<catalog>节点并单次处理cd,无法遍历所有<cd>元素

正确XSLT代码

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
    <!-- 匹配catalog节点,触发子cd元素的模板处理 -->
    <xsl:template match="catalog">
        <xsl:apply-templates select="cd"/>
    </xsl:template>

    <!-- 匹配单个cd节点,处理nominee属性的条件逻辑 -->
    <xsl:template match="cd">
        <fo:block>
            <xsl:choose>
                <xsl:when test="starts-with(@nominee, '1 2')">
                    <xsl:value-of select="@nominee"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="concat('1 2 ', @nominee)"/>
                </xsl:otherwise>
            </xsl:choose>
        </fo:block>
    </xsl:template>
</xsl:stylesheet>

最终输出结果

<fo:block>1 2 First</fo:block>
<fo:block>1 2 Second</fo:block>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:05:19