Search code examples
stringparsingxsltfxsl

Can an XSLT parse a string of text?


This is my first time using XSLT. I'm trying to create a file that will convert an XML data file exported from a program I use to an HTML report.

One of the element's value is path to an image file, but the path generated is an absolute path such as

C:\Documents and Settings\me\Desktop\xml export\cd000402.jpg

but I want a relative path to just the file name.

Is there some way through the XLST file to parse out the file name?


Solution

  • XPath contains the substring-after function which returns the string following the first occurrence of another string. This isn't enough by itself, but a template such as the following might do it:

    <xsl:template name="filename-only">
        <xsl:param name="path" />
        <xsl:choose>
            <xsl:when test="contains($path, '\')">
                <xsl:call-template name="filename-only">
                    <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 set of string functions available is not terribly extensive, but I've found that it is good enough for most applications that you'll need in XSLT.