最后一个空格 XSLT 之前的子字符串



我有一个长度为 30 的名称字段,如下所示:

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

我需要在最后一个空格之前进行子字符串。所以我需要使用 xslt 以下内容:

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

I.下面是一个纯 XSLT 1.0 解决方案

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>

<xsl:template match="Name/text()" name="trimRight">
<xsl:param name="pText" select="."/>

<xsl:choose>
<xsl:when test="not(substring($pText, string-length($pText)) = ' ')">
<xsl:value-of select="$pText"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="trimRight">
<xsl:with-param name="pText" 
select="substring($pText, 1, string-length($pText) -1)"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>

当此转换应用于以下 XML文档(派生自 OP 提供的文档,但在中间空格段中具有不同数量的空格)时:

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

生成所需的正确结果

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

请注意:与使用normalize-space()从任何仅包含空格的最长连续子字符串中删除除一个空格之外的所有空格不同,此解决方案保留了空格的所有中间段。

<小时 />

二.XSLT 2.0 解决方案

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Name/text()">
<xsl:sequence select="replace(., 's+$', '')"/>
</xsl:template>
</xsl:stylesheet>

当此转换应用于同一 XML 文档(如上)时,将生成相同的正确结果

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

我同意 @michael.hor257k

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="3.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="#all">
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="Name/text()">
<xsl:sequence select="normalize-space(.)" />
</xsl:template>

</xsl:stylesheet>

带输入

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

生产

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

最新更新