XSL:split-string function

One of the reasons I like developing for SharePoint is that I get to work with many different technologies and platforms.  When I am designing a custom list for (display, edit or new), There are times where I may have a delimited string in a field that I want to display differently on the screen.  Since the forms are all XSL style sheets, it is helpful to have a few XSL templates to process the data.

I wrote this XSL template so I could wrap some HTML around any element in a delimited list.  This is specifically geared towards XSL 1.0.  In XSL 2.0, I would most likely use tokenize.  I’m not an expert at XSL so if anyone has any suggestions that would improve this template, please leave comments.

<xsl:template name="split-string">
<xsl:param name="list" />
<xsl:param name="delimiter" />
<xsl:param name="id" />
<xsl:if test="normalize-space($list)">
<xsl:variable name="newlist">
<xsl:when test="contains($list, $delimiter)">
<xsl:value-of select="normalize-space($list)" />
<xsl:value-of select="concat(normalize-space($list), $delimiter)"/>

<xsl:variable name="first" select="substring-before($newlist, $delimiter)" />
<xsl:variable name="remaining" select="substring-after($newlist, $delimiter)" />
<!-- This is where you need to put the display code -->
<xsl:attribute name="href">./Attachments/<xsl:value-of select="$id" />/<xsl:value-of select="$first" /></xsl:attribute>
<xsl:attribute name="target">_blank</xsl:attribute>
<img src="~/_layouts/images/doclink.gif" width="16" height="16" alt="" border="0" />
<xsl:value-of select="$first" />
<!--  end display code -->
<xsl:if test="$remaining">
<!-- I put a little display code here also -->
<br />
<!-- end display code -->
<xsl:call-template name="split-string">
<xsl:with-param name="list" select="$remaining" />
<xsl:with-param name="delimiter">
<xsl:value-of select="$delimiter"/>
<xsl:with-param name="id"><xsl:value-of select="$id" /></xsl:with-param>

You can add or remove variables depending on what you need. In the above example code, I had a semi-colon list of email attachment file names that were attached to the list. I wanted to create a ‘clickable’ link to each file, which is why I needed the ID field. Normally, you wouldn’t need the ID field.

This is how I called the template in my XSL:

<xsl:call-template name="split-string">
<xsl:with-param name="list"><xsl:value-of select="@EmailAttachmentNames" /></xsl:with-param>
<xsl:with-param name="delimiter">;</xsl:with-param>
<xsl:with-param name="id"><xsl:value-of select="@ID" /></xsl:with-param>

Leave a Reply

Your email address will not be published. Required fields are marked *