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

XSLT 1.0字符串位置调整求助:字符前后移动及固定值添加

XSLT逻辑修改求助

输入数据

<item>
    <OBJ_CODE>(01)04030539083706(21)81490930005891136867</OBJ_CODE>
</item>
<item>
    <OBJ_CODE>(01)04030539083706(21)81490930005891143208</OBJ_CODE>
</item>

预期输出

<SN>(01)04030539083706(21)0005891136867(A99)8149093</SN>
<SN>(01)04030539083706(21)0005891136867(A99)8149093</SN>

需求说明

将OBJ_CODE中(21)后的内容拆分为前7位和后13位,重组为:(01)部分 + (21) + 后13位 + (A99) + 前7位,最终封装到<SN>标签中。

当前XSLT代码

<xsl:template match="item">
        <SN>
            <xsl:choose>
                <xsl:when test="../../EncodingType = 'SSCC'">
                    <xsl:value-of select="substring(OBJ_CODE,1,23)"/><xsl:value-of select="substring(OBJ_CODE,30,13)"/>(A99)<xsl:value-of select="substring(OBJ_CODE,23,7)"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="OBJ_CODE"/>
                </xsl:otherwise>
            </xsl:choose>
            <xsl:value-of select="NUMBER"/>
        </SN>
</xsl:template>

修正后的XSLT代码

当前代码依赖硬编码的字符串索引,若(01)后内容长度变化会失效,建议改用字符串定位函数实现更健壮的逻辑:

<xsl:template match="item">
    <SN>
        <xsl:choose>
            <xsl:when test="../../EncodingType = 'SSCC'">
                <!-- 提取(21)之前的所有内容 -->
                <xsl:variable name="preContent" select="substring-before(OBJ_CODE, '(21)')"/>
                <!-- 提取(21)之后的所有内容 -->
                <xsl:variable name="post21Content" select="substring-after(OBJ_CODE, '(21)')"/>
                <!-- 按需求重组字符串 -->
                <xsl:value-of select="concat($preContent, '(21)', substring($post21Content, 8, 13), '(A99)', substring($post21Content, 1, 7))"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="OBJ_CODE"/>
            </xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select="NUMBER"/>
    </SN>
</xsl:template>

修正说明

  • 用substring-before和substring-after精准定位(21)位置,避免硬编码索引的局限性
  • 通过变量拆分+concat函数清晰实现重组逻辑,代码可读性和可维护性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:40:17