Skip to content

Instantly share code, notes, and snippets.

@netsi1964
Created May 9, 2012 21:05
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save netsi1964/2648824 to your computer and use it in GitHub Desktop.
Save netsi1964/2648824 to your computer and use it in GitHub Desktop.
XSLT split a string into items
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:output method="xml" indent="no"/>
<xsl:variable name="groups" select="'265, 256'" />
<xsl:template match="root">
<xsl:variable name="items">
<xsl:call-template name="splitStringToItems">
<xsl:with-param name="delimiter" />
<xsl:with-param name="list" select="$groups" />
</xsl:call-template>
</xsl:variable>
<xsl:if test="msxsl:node-set($items)/item[text()='256']">
You are a member of group 256
</xsl:if>
</xsl:template>
<xsl:template name="splitStringToItems">
<xsl:param name="list" />
<xsl:param name="delimiter" select="','" />
<xsl:variable name="_delimiter">
<xsl:choose>
<xsl:when test="string-length($delimiter)=0">,</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$delimiter"/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:variable name="newlist">
<xsl:choose>
<xsl:when test="contains($list, $_delimiter)">
<xsl:value-of select="normalize-space($list)" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="concat(normalize-space($list), $_delimiter)"/>
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:variable name="first" select="substring-before($newlist, $_delimiter)" />
<xsl:variable name="remaining" select="substring-after($newlist, $_delimiter)" />
<item>
<xsl:value-of select="$first" />
</item>
<xsl:if test="$remaining">
<xsl:call-template name="splitStringToItems">
<xsl:with-param name="list" select="$remaining" />
<xsl:with-param name="delimiter" select="$_delimiter" />
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
@netsi1964
Copy link
Author

This XSLT document contains a template which can split the content of a string into a collection of items.
If you for instance have a string: "265, 256" you will get a collection like this:
<item>265</item>
<item>256</item>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment