htmlxmlxslt

How to find last to preview work and store to my field in xslt?


How to find last to preview word in xslt?

I have this code like this

<tag>news/economy/policy/raghuram-rajan-sheds-dogmatism-in-policy-meet-makes-next-rbi-governors-job-easier</tag>

I want to search to last this word "/" and

I want the result to be policy.


Solution

  • To do this in pure XSLT 1.0, with no extensions, use:

    <xsl:template name="token-before-last">
        <xsl:param name="text"/>
        <xsl:param name="delimiter" select="'/'"/>
        <xsl:variable name="next-text" select="substring-after($text, $delimiter)" />
        <xsl:choose>
            <xsl:when test="contains($next-text, $delimiter)">
                <!-- recursive call -->
                <xsl:call-template name="token-before-last">
                    <xsl:with-param name="text" select="$next-text"/>
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="substring-before($text, $delimiter)"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    

    Example of call:

    <xsl:template match="tag">
        <result>
            <xsl:call-template name="token-before-last">
                <xsl:with-param name="text" select="."/>
            </xsl:call-template>
        </result>
    </xsl:template>
    

    Demo: http://xsltransform.net/94AbWAB


    If your processor supports the EXSLT str:tokenize() extension function, you can do simply:

    <xsl:template match="tag">
        <result>
            <xsl:value-of select="str:tokenize(., '/')[last() -1]"/>
        </result>
    </xsl:template>
    

    Demo: http://xsltransform.net/94AbWAB/1