Substring after the last character in xslt

I can not find the exact answer to this question, so I hope someone helps me here.

I have a string and I want to get the substring after the last ".". I am using xslt 1.0.

How it's done? This is my code.

<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> 

When I insert the suggested code, I get an error message. "XSLT stylesheet parsing failed."

+6
source share
4 answers

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> 
+14
source

I made the same behavior using the xsl function: - use is then a little easier:

 <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 the value:

 <xsl:value-of select="ns:substring-after-last(.,'=')" xmlns:ns="yourNamespace"/> 
+3
source

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> 

( if here, because if your string ends with a separator, tokenize does not return an empty string)

+1
source

I allowed him

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

Not necessary

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

in a template call

0
source

Source: https://habr.com/ru/post/948704/


All Articles