XSLT: Extract file name from path

When transforming the WordProcessingML documents, I wanted to output an IMG element that would contain the HREF attribute equal to the picture name used in the Word file (assuming the picture is linked, not just inserted). However, the picture name in the Word file usually contains whole path (even when the picture and the Word document are in the same directory), so I needed a function that would extract the file name from the path. As XSLT 1.0 has very limited function set (and MSMXL still doesn't support XSLT 2.0), I had to write the function myself using a named template:
<xsl:template name="fileName">
  <xsl:param name="path" />
  <xsl:choose>
    <xsl:when test="contains($path,'\')">
      <xsl:call-template name="fileName">
        <xsl:with-param name="path" select="substring-after($path,'\')" />
      </xsl:call-template>
    </xsl:when>
    <xsl:when test="contains($path,'/')">
      <xsl:call-template name="fileName">
        <xsl:with-param name="path" select="substring-after($path,'/')" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$path" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

The function recognizes Windows- and Unix-style paths (forward and backward slashes are recognized as path delimiters).

5 comments:

Lav said...

Nice blog. Check out my template to split a string

Anonymous said...

Thanks this was just what I needed for my transform.

sizu said...

Great code!

I had to convert a input path to a filename to place in the folder tag. I convert all slashes to forward slashes before calling the template.


\
/

























www.izuservices.com

Neil said...

Thank you
It is very useful !

Here is how you call this function




Neil said...

xsl:call-template name="fileName"
xsl:with-param name="path" select=""
xsl:call-template

Post a Comment