如何使用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
相关产品推荐
相关产品推荐

