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

如何使用XSLT截取名称字段最后一个空格前的内容?

XSLT 去除名称字段末尾空格的解决方案

需求说明

处理固定长度为30的<Name>字段,去除字段值末尾的所有填充空格,保留有效名称内容:

原始输入:

<Name>Rainbow Charity             </Name>
<Name>Ben Tromy Jig               </Name>

期望输出:

<Name>Rainbow Charity</Name>
<Name>Ben Tromy Jig</Name>

解决方案

方案1:XSLT 2.0及以上版本(正则替换实现)

利用replace()函数匹配末尾连续空格并替换为空,代码简洁高效:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <!-- 匹配并处理Name节点 -->
  <xsl:template match="Name">
    <Name>
      <!-- 替换末尾所有连续空格 -->
      <xsl:value-of select="replace(., '\s+$', '')"/>
    </Name>
  </xsl:template>

  <!-- 默认模板:保留原文档其他节点结构 -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

方案2:XSLT 1.0版本(递归模板实现)

XSLT 1.0无内置正则函数,通过递归模板逐字符检查并去除末尾空格:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <!-- 匹配并处理Name节点 -->
  <xsl:template match="Name">
    <Name>
      <xsl:call-template name="trim-trailing-spaces">
        <xsl:with-param name="text" select="."/>
      </xsl:call-template>
    </Name>
  </xsl:template>

  <!-- 递归去除末尾空格的模板 -->
  <xsl:template name="trim-trailing-spaces">
    <xsl:param name="text"/>
    <xsl:choose>
      <!-- 检查最后一个字符是否为空格,若是则递归截取前n-1个字符 -->
      <xsl:when test="substring($text, string-length($text)) = ' '">
        <xsl:call-template name="trim-trailing-spaces">
          <xsl:with-param name="text" select="substring($text, 1, string-length($text) - 1)"/>
        </xsl:call-template>
      </xsl:when>
      <!-- 无末尾空格时返回处理后的文本 -->
      <xsl:otherwise>
        <xsl:value-of select="$text"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <!-- 默认模板:保留原文档其他节点结构 -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:24:48