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

XSLT中添加<xsl:if>后代码报错,移除则正常,问题出在哪?

问题原因:<xsl:sort>的位置违反XSLT语法规范

你这段代码报错的核心问题是**<xsl:sort>被嵌套在了<xsl:if>内部**,而根据XSLT的语法规则:<xsl:sort>必须作为<xsl:for-each>的直接子节点存在,不能被任何其他元素(包括条件判断标签)包裹。

<xsl:sort>的作用是定义循环节点的排序逻辑,它需要在循环执行前就确定规则,因此必须直接放在<xsl:for-each>的子层级,哪怕你的<xsl:if>条件永远成立,这种嵌套写法也会触发语法解析错误。

修正后的代码

将<xsl:sort>移到<xsl:if>外部,作为<xsl:for-each>的第一个子元素即可:

<xsl:for-each select="$external-doc/document(.)/items/item">
    <xsl:sort select="concat(substring(pubDate,7,4), substring(pubDate,1,2),substring(pubDate,4,2))" order="descending"/>
    <xsl:if test="contains('apple','ap')">
        <item>
            <xsl:attribute name="href" select="concat($base-url,@href)"/>
            <xsl:apply-templates select="attribute()[not(name() = 'href')]|node()[not(name() = 'hero-image') and not(name() = 'image')]" /> 
            <xsl:if test="image">
                <image>
                    <xsl:choose>
                        <xsl:when test="not(contains(image/img/@src,'://'))">
                            <img>
                                <xsl:attribute name="src" select="concat($base-url,image/img/@src)"/>
                                <xsl:apply-templates select="image/img/attribute()[not(name() = 'src')]" />
                            </img>
                        </xsl:when>
                        <xsl:otherwise><xsl:apply-templates select="image/img" /></xsl:otherwise>
                    </xsl:choose>
                </image>
            </xsl:if>
            <searchtags>{string-join(tags/tag, ',')}</searchtags>
        </item> 
    </xsl:if>
</xsl:for-each>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:22:40