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

如何使用XSLT移除属性字符串中的最后N个令牌?

通用移除属性最后N个令牌的XSLT实现

针对你需要移除infoEntityIdent属性最后2个以-分隔令牌的需求,以下是符合通用编程规范的解决方案,无需依赖固定的令牌数量:

XSLT 2.0+ 简洁实现

利用XSLT 2.0及以上版本提供的tokenize和string-join函数,可快速实现通用逻辑:

<!-- 先获取目标属性值 -->
<xsl:variable name="ident-value" select="//figure[@id = current()/@internalRefId]/graphic/@infoEntityIdent"/>

<!-- 拆分令牌、保留前(总数量-2)个、重新拼接 -->
<xsl:variable name="tokens" select="tokenize($ident-value, '-')"/>
<xsl:value-of select="string-join(subsequence($tokens, 1, count($tokens) - 2), '-')"/>

代码说明:

  • tokenize($ident-value, '-'):将属性值按-拆分为令牌序列
  • count($tokens) - 2:计算需要保留的令牌数量(总令牌数减去要移除的2个)
  • subsequence($tokens, 1, count($tokens)-2):截取序列中前N个令牌(N=总数量-2)
  • string-join(..., '-'):将截取后的令牌用-重新拼接为字符串

XSLT 1.0 兼容实现

如果需要兼容不支持XSLT 2.0的环境,可使用递归模板实现:

<!-- 递归模板:移除指定数量的末尾令牌 -->
<xsl:template name="remove-last-tokens">
    <xsl:param name="input-string"/>
    <xsl:param name="remove-count" select="2"/>
    <xsl:param name="delimiter" select="-"/>
    
    <xsl:choose>
        <!-- 终止条件:移除数量为0,或已无分隔符 -->
        <xsl:when test="$remove-count = 0 or not(contains($input-string, $delimiter))">
            <xsl:value-of select="$input-string"/>
        </xsl:when>
        <xsl:otherwise>
            <!-- 截断到最后一个分隔符之前,递归调用 -->
            <xsl:call-template name="remove-last-tokens">
                <xsl:with-param name="input-string" select="substring($input-string, 1, string-length($input-string) - string-length(substring-after($input-string, $delimiter)) - 1)"/>
                <xsl:with-param name="remove-count" select="$remove-count - 1"/>
                <xsl:with-param name="delimiter" select="$delimiter"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

使用方式:

<xsl:variable name="ident-value" select="//figure[@id = current()/@internalRefId]/graphic/@infoEntityIdent"/>
<xsl:call-template name="remove-last-tokens">
    <xsl:with-param name="input-string" select="$ident-value"/>
    <xsl:with-param name="remove-count" select="2"/>
</xsl:call-template>

代码说明:

递归地查找并截断字符串的最后一个令牌及分隔符,重复执行remove-count次,直到完成移除操作。


内容的提问来源于stack exchange,提问作者Stéphane Dubois

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:25:28