7

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?

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
Eric Anastas
  • 21,675
  • 38
  • 142
  • 236

5 Answers5

12

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.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
2

This is a little beyond the scope of the question, but Michael Kay has an excellent paper on using XSLT 2 to parse pure text into XML.

James Sulak
  • 31,389
  • 11
  • 53
  • 57
2

Yes, see a general LR(1) parser implemented in XSLT 2.0. (just in 245 lines).

I have implemented with it a parser for JSON and a parser for XPath 2.0 -- entirely in XSLT.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
0

XSLT with the help of XPath 2.0 and its various string functions helps it deal with this type of things.

Example:
Assuming the path [to jpg file] mentioned in question comes from an xml snippet similar to

...
<For_HTML>
   <Image1>
      <Path>C:\Documents and Settings\me\Desktop\xml export\cd000402.jpg</Path>
      <Description>Photo of the parking lot</Description>
      <Width>123</Width>
      ...
    </Image1>
</For_HTML>

XSLT snippet would look something like

<xsl:template match='//For_HTML/Image1'> 
     <img src='http://myNewServer.com/ImageBin/{substring-after(./Path,"\xml export\")}'
          alt='{./Description}'
          width=' ....  you got the idea'
     /> 
</xsl:template>

Note: didn't have time to test; but that looks about right.

mjv
  • 73,152
  • 14
  • 113
  • 156
0

It is possible. I've developed the following script: http://barsand.wordpress.com/2012/06/19/can-an-xslt-parse-a-string-of-text/

Dan
  • 1