Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a last word from a string in xslt

Tags:

xslt

xpath

I just want to take the last element from a string which is like this "aaa-bbb-ccc-ddd" in xslt.

Out put should be "ddd" irrecspective of '-'s.

like image 375
Satoshi Avatar asked Nov 15 '11 06:11

Satoshi


People also ask

How do I select a substring in XSLT?

XSLT doesn't have any new function to search Strings in a reverse manner. We have substring function which creates two fields substring-before-last and substring-after-last.In XSLT it is defined as follows: <xsl:value-of select="substring (string name ,0, MAX_LENGTH )"/>...

What is substring after in XSLT?

substring-after() Function — Returns the substring of the first argument after the first occurrence of the second argument in the first argument. If the second argument does not occur in the first argument, the substring-after() function returns an empty string.

What is text () in XSLT?

XSLT <xsl:text> The <xsl:text> element is used to write literal text to the output. Tip: This element may contain literal text, entity references, and #PCDATA.


1 Answers

XSLT/Xpath 2.0 - using the tokenize() function to split the string on the "-" and then use a predicate filter to select the last item in the sequence:

<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <xsl:value-of select="tokenize('aaa-bbb-ccc-ddd','-')[last()]"/>
    </xsl:template>
</xsl:stylesheet>

XSLT/XPath 1.0 - using a recursive template to look for the last occurrence of "-" and selecting the substring following it:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <xsl:call-template name="substring-after-last">
            <xsl:with-param name="input" select="'aaa-bbb-ccc-ddd'" />
            <xsl:with-param name="marker" select="'-'" />
        </xsl:call-template>
    </xsl:template>

    <xsl:template name="substring-after-last">
        <xsl:param name="input" />
        <xsl:param name="marker" />
        <xsl:choose>
            <xsl:when test="contains($input,$marker)">
                <xsl:call-template name="substring-after-last">
                    <xsl:with-param name="input"
          select="substring-after($input,$marker)" />
                    <xsl:with-param name="marker" select="$marker" />
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="$input" />
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>
like image 183
Mads Hansen Avatar answered Nov 15 '22 21:11

Mads Hansen