I can't find the exact answer for this question so I hope someone will help me here.
I have a string and I want get the substring after the last '.'. I'm using xslt 1.0.
How is this done? This is my code.
<xsl:choose>
<xsl:otherwise>
<xsl:attribute name="class">method txt-align-left case-names</xsl:attribute> 
<xsl:value-of select="./@name"/> // this prints a string eg: 'something1.something2.something3'
</xsl:otherwise>
</xsl:choose>
When i paste the suggested code I get an error message. "Parsing an XSLT stylesheet failed."
I can't think of a way to do this with a single expression in XSLT 1.0, but you can do it with a recursive template:
<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>
Result:
<n>something3</n>
I did the same behaviour with a xsl:function - usage is then a little bit simpler:
<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>
And you can call it directly in a value-of:
<xsl:value-of select="ns:substring-after-last(.,'=')" xmlns:ns="yourNamespace"/>
Here is a solution using EXSLT str:tokenize:
<xsl:if test="substring($string, string-length($string)) != '.'"><xsl:value-of select="str:tokenize($string, '.')[last()]" /></xsl:if>
(the if
is here because if your string ends with the separator, tokenize won't return an empty string)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With