Pages

Tuesday, August 21, 2012

Modularizing XSLT code (extract file name from path)

Few days back I came across a requirement where I had to determine the name of a file given the absolute path. Had it been java or any other popular programming language I could just tokenize the path with the directory separator character ("/" or "") and taken the last token. However doing it in XSLT 1.0 was bit tricky. A recursive function (templates in case of XSLT 1.0 ) call was required."substring-after" function gives the part of the string after the first occurrence of a given delimiter.

[sourcecode language="xml"]
<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>

[/sourcecode]



And to call above code , we have to write the following fragment
[sourcecode language="xml"]
<xsl:call-template name="fileName">
<xsl:with-param name="path" select="D:codetest.txt"/>
</xsl:call-template>
[/sourcecode]

If XMLT 2.0 is available the above job is much easier using base-uri()