Search code examples
xslttokentokenize

How to remove last N tokens in a string with XSLT?


I need to remove the last N tokens of an attribute, in this case the last 2 tokens for infoEntityIdent :

Here is the element <graphic infoEntityIdent="XXX-XXXXXX-X-781410-P-77445-00256-A-000-01">

The result would be XXX-XXXXXX-X-781410-P-77445-00256-A

I sort of got it working using the following XSLT:

<xsl:analyze-string select="//figure[@id = current()/@internalRefId]/graphic/@infoEntityIdent" 
                                        regex="-">
    <xsl:matching-substring>
        <xsl:if test="position() le 14">
            <xsl:value-of select="."/>
        </xsl:if>
    </xsl:matching-substring>
    <xsl:non-matching-substring>
        <xsl:if test="position() le 15">
            <xsl:value-of select="."/>
        </xsl:if>
    </xsl:non-matching-substring>
</xsl:analyze-string>

The problem is that this is not good programming practice as it will only work as long as we have 10 tokens separated by "-".

I would like to just remove the last 2 tokens and the "-" to end with XXX-XXXXXX-X-781410-P-77445-00256-A


Solution

  • You can do simply:

    <xsl:value-of select="tokenize($yourString, '-')[position() le last() - 2]" separator="-"/>
    

    Added:

    Just for fun, here is a way to look at it from (literally) another direction:

    <xsl:value-of select="reverse(subsequence(reverse(tokenize($yourString,, '-')), 3))" separator="-"/>