Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse Find in a string

Tags:

xml

xslt

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.

like image 260
Xetius Avatar asked Aug 18 '08 12:08

Xetius


People also ask

Does Reverse () work on strings?

reverse() works like reversing the string in place. However, what it actually does is create a new string containing the original data in reverse order.

How do you find last occurrence of a character in a string in Excel?

Here is how this works: LastPosition – which is our custom function – returns the position of the forward-slash. This function takes two arguments – the cell reference that has the URL and the character whose position we need to find. RIGHT function then gives us all the characters after the forward slash.


1 Answers

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>
like image 148
samjudson Avatar answered Nov 03 '22 15:11

samjudson