xslt中最后一个字符后的子串

时间:2013-07-04 11:16:14

标签: xslt

我找不到这个问题的确切答案,所以我希望有人会帮助我。

我有一个字符串,我希望在最后一个'。'后得到子字符串。我正在使用xslt 1.0。

这是怎么做到的?这是我的代码。

<xsl:choose>
    <xsl:otherwise> 
        <xsl:attribute name="class">method txt-align-left case-names</xsl:attribute>&#160;
        <xsl:value-of select="./@name"/> // this prints a string eg: 'something1.something2.something3'
    </xsl:otherwise>
</xsl:choose>

当我粘贴建议的代码时,我收到一条错误消息。 “解析XSLT样式表失败。”

4 个答案:

答案 0 :(得分:16)

我想不出用XSLT 1.0中的单个表达式来做到这一点的方法,但你可以使用递归模板来做到这一点:

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

  <xsl:template match="/">
    <n>
      <xsl:call-template name="GetLastSegment">
        <xsl:with-param name="value" select="'something1.something2.something3'" />
        <xsl:with-param name="separator" select="'.'" />
      </xsl:call-template>
    </n>
  </xsl:template>

  <xsl:template name="GetLastSegment">
    <xsl:param name="value" />
    <xsl:param name="separator" select="'.'" />

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

结果:

<n>something3</n>

答案 1 :(得分:3)

我用xsl:function做了同样的行为 - 用法稍微简单一些:

<xsl:function name="ns:substring-after-last" as="xs:string" xmlns:ns="yourNamespace">
    <xsl:param name="value" as="xs:string?"/>
    <xsl:param name="separator" as="xs:string"/>        
    <xsl:choose>
        <xsl:when test="contains($value, $separator)">
            <xsl:value-of select="ns:substring-after-last(substring-after($value, $separator), $separator)" />
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$value" />
        </xsl:otherwise>
    </xsl:choose>
</xsl:function>

你可以直接用值 -

来调用它
<xsl:value-of select="ns:substring-after-last(.,'=')" xmlns:ns="yourNamespace"/>  

答案 2 :(得分:1)

以下是使用EXSLT str:tokenize的解决方案:

<xsl:if test="substring($string, string-length($string)) != '.'"><xsl:value-of select="str:tokenize($string, '.')[last()]" /></xsl:if> 

if在这里,因为如果你的字符串以分隔符结尾,则tokenize不会返回空字符串)

答案 3 :(得分:0)

我解决了它

<xsl:call-template name="GetLastSegment">
<xsl:with-param name="value" select="./@name" />
</xsl:call-template>

不需要

<xsl:with-param name="separator" value="'.'" />

在模板调用中

相关问题