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

如何在XSLT的xsl:apply-templates中实现带条件的参数传递?

解决XSLT中apply-templates参数的条件赋值问题

嗨,这个问题我太熟了!你说的不能在xsl:apply-templates里直接用xsl:choose其实是个常见误区——不是不能用,而是得把它放在**xsl:with-param的内部**,或者换个更简洁的方式用XPath条件表达式来实现。下面给你几种可行的方案:

方案1:直接在xsl:with-param里嵌套xsl:choose(最直观,兼容所有XSLT版本)

其实你原来的条件逻辑完全可以直接放到xsl:with-param的内容里,写法是合法的,可能之前你没放对位置?试试这个:

<xsl:apply-templates select="Header/Amounts/Totals/TotalLineAmount[string(text())]" mode="MOALoop">
    <xsl:with-param name="qualifier">
        <xsl:choose>
            <xsl:when test="$imdQualifier != ''">
                <xsl:value-of select="$imdQualifier"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="'203'"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:with-param>
</xsl:apply-templates>

这个写法的核心是:xsl:with-param不仅支持用select属性直接传值,还可以在它的内部写模板逻辑(包括xsl:choose),最终把逻辑生成的结果作为参数值传递。

方案2:用XPath的if-then-else表达式(更简洁,XSLT 2.0+适用)

如果你的环境支持XSLT 2.0或更高版本,直接用XPath的条件表达式会更简洁,把逻辑写在select属性里就行:

<xsl:apply-templates select="Header/Amounts/Totals/TotalLineAmount[string(text())]" mode="MOALoop">
    <xsl:with-param name="qualifier" select="if ($imdQualifier != '') then $imdQualifier else '203'"/>
</xsl:apply-templates>

这种写法把条件判断直接整合到参数的选择器中,代码更紧凑,可读性也很强。

方案3:兼容XSLT 1.0的简洁写法

如果必须兼容XSLT 1.0(它不支持if-then-else表达式),可以用string-length结合substring来实现条件赋值:

<xsl:apply-templates select="Header/Amounts/Totals/TotalLineAmount[string(text())]" mode="MOALoop">
    <xsl:with-param name="qualifier" select="concat(
        substring($imdQualifier, 1, string-length($imdQualifier) > 0),
        substring('203', 1, string-length($imdQualifier) = 0)
    )"/>
</xsl:apply-templates>

原理是:当$imdQualifier不为空时,第一个substring会返回它的全部内容,第二个返回空;反之则第一个返回空,第二个返回'203',最后用concat拼接起来得到最终值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:58:38