Question

I need to be able to find the last occurrence of a character within an element.

For example:

<mediaurl>http://www.blah.com/path/to/file/media.jpg</mediaurl>

If I try to locate it through using substring-before(mediaurl, '.') and substring-after(mediaurl, '.') then it will, of course, match on the first dot.

How would I get the file extension? Essentially, I need to get the file name and the extension from a path like this, but I am quite stumped as to how to do it using XSLT.

Was it helpful?

Solution

The following is an example of a template that would produce the required output in XSLT 1.0:

<xsl:template name="getExtension">
<xsl:param name="filename"/>

  <xsl:choose>
    <xsl:when test="contains($filename, '.')">
    <xsl:call-template name="getExtension">
      <xsl:with-param name="filename" select="substring-after($filename, '.')"/>
    </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$filename"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

<xsl:template match="/">
    <xsl:call-template name="getExtension">
        <xsl:with-param name="filename" select="'http://www.blah.com/path/to/file/media.jpg'"/>
    </xsl:call-template>
</xsl:template>

OTHER TIPS

If you're using XSLT 2.0, it's easy:

 <xsl:variable name="extension" select="tokenize($filename, '\.')[last()]"/>

If you're not, it's a bit harder. There's a good example from the O'Reilly XSLT Cookbook. Search for "Tokenizing a String."

I believe there's also an EXSLT function, if you have that available.

How about tokenize with "/" and take the last element from the array ?

Example: tokenize("XPath is fun", "\s+")
Result: ("XPath", "is", "fun")

Was an XSLT fiddler sometime back... lost touch now. But HTH

For reference, this problem is usually called "substring-after-last" in XSLT.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top