Here at CorasWorks, the ability to leverage XSLT 2.0 within our SharePoint-based applications – thanks to the CorasWorks Application Service – has added a lot in the way of efficiency. We’ve previously blogged about the myriad of Date Formatting options (here), and using RegEx to parse content from the ugly HTML markup SharePoint creates for multi-line text fields (here). Another area though that has improved vastly with XSLT 2.0 is string functions; specifically, let’s look at the tokenize(), string-join() and distinct-values() functions.
As is often the case, it’s not that these sort of routines weren’t possible in XSLT 1.0; they were just inefficient, took more lines of script to write and were possibly even prohibitively complex to come up with on your own. The new functions in XSLT 2.0, by contrast, are optimized, compact and intuitive to write.
Take splitting a string based on some delimiter, a fairly common use case; using the tokenize() function within a for-each statement makes this trivial. For example, SharePoint frequently stores certain data as a string delimited by the characters “;#” – item attachments and multi-select Choice, Person & Lookup values are just some of the data points SharePoint stores in this format. With XSLT 2.0, these values could be parsed out simply as such:
The inverse is also equally straightforward; assume you have an XML node set you’d like to concatenate the values for using some delimiter of your choosing. This example would take the Assigned To values for all Tasks and join them into a single element called “StringJoin” with each value separated by a semicolon and a space using the string-join() function:
<xsl:value-of select=”string-join(Tasks/AssignedTo/text(),’; ‘)”/>
Following that example though, if more than one Task is assigned to the same person, you’d get duplicate names in the “StringJoin” value; so let’s see how a node set could be created with just the distinct names via the distinct-values() function:
These three functions go a long way to optimizing and simplifying the XSLT you may write, and we’re lucky to be the only application platform on SharePoint that supports them and all the other advantages XSLT 2.0 affords!