tags:

views:

1639

answers:

4

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

for example:

<mediaurl><http://www.blah.com/path/to/file/media.jpg&gt;&lt;/mediaurl&gt;

If I try to locate 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.

A: 

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

Gishu
A: 

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.

James Sulak
+6  A: 

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'"/&gt;
    </xsl:call-template>
</xsl:template>
samjudson
A: 

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

jelovirt