XSLT 1.0版需要拔出字符串的最后一个字

时间:2013-02-13 16:50:29

标签: xslt xpath

我需要从以下字符串中取出姓氏的最后一个单词:

<CUSTOMER_x0020_NAME>Mr Tim Cookson</CUSTOMER_x0020_NAME>

所以我只需要使用XSLT拔出'Cookson',我该怎么做?试过几个关系到子串 - 但没有运气。

2 个答案:

答案 0 :(得分:2)

这是一个非递归解决方案,适用于任何非字母字符的字分隔符(但最后一个字后面的字符,如果有的话,应该只是空格):

<xsl:stylesheet version="1.0" 
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:param name="pLower" select=
  "'abcdefghijklmnopqrstuvwxyz'"/>

 <xsl:param name="pUpper" select=
  "'ABCDEFGHIJKLMNOPQRSTUVWXYZ'"/>

 <xsl:variable name="vAlpha" select="concat($pUpper, $pLower)"/>

 <xsl:template match="text()">
  <xsl:variable name="vText" select="normalize-space()"/>
  <xsl:variable name="vLength" select="string-length($vText)"/>
  <xsl:variable name="vPunct" select="translate(., $vAlpha, '')"/>

  <xsl:for-each select=
      "document('')//node()
      |document('')//@*
      |document('')//namespace::*">
   <xsl:variable name="vPos" select="position()"/>
   <xsl:variable name="vRemaining" 
                 select="substring($vText, $vPos)"/>

   <xsl:if test=
    "contains($vPunct, substring($vRemaining,1,1))
    and
     $vLength -$vPos 
       = string-length(translate($vRemaining, $vPunct, ''))
    ">
     <xsl:value-of select="substring($vRemaining,2)"/>
   </xsl:if>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

在提供的XML文档上应用此转换时:

<CUSTOMER_x0020_NAME>Mr Tim Cookson</CUSTOMER_x0020_NAME>

产生了想要的正确结果:

Cookson

对此XML文档应用相同的转换时

<CUSTOMER_x0020_NAME>Mr. Tim Berners-Lee</CUSTOMER_x0020_NAME>

再次产生正确的结果:

Lee

答案 1 :(得分:0)

您可以使用此递归模板获取值的最后一个单词:

  <xsl:template name="GetLastWord">
    <xsl:param name="value" />
    <xsl:variable name="normalized" select="normalize-space($value)" />

    <xsl:choose>
      <xsl:when test="contains($normalized, ' ')">
        <xsl:call-template name="GetLastWord">
          <xsl:with-param name="value" select="substring-after($normalized, ' ')" />
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$normalized"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

您可以将此模板添加到XSLT中,然后只需调用它,如下所示:

  <xsl:call-template name="GetLastWord">
    <xsl:with-param name="value" select="CUSTOMER_x0020_NAME" />
  </xsl:call-template>