Tokenizing Delimited String inside an XSL

If your requirement is to split a node value in an XML, that contains a delimited string of value, into individual items, then you have reached the right place … have a look at the example below. If you are familiar with a little bit of XML and XSL … I don’t think you would need any explanation.
Also, this example includes usage of XSL functions like xsl:call-template , xsl:substring-before, xsl:substring-after, if that’s what you are after.

XML to be transformed (food.xml):-
Assume the task is to tokenize the string delimited by comma, in the the tag “keywords”

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="food.xsl"?>
<food>
<date>July 2008</date>
<description>All about things we eat everyday</description>
<keywords>Fruits, Vegetables, Pulses, Meat, Cereals </keywords>
</food>

XSL (food.xsl):-

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="utf-8" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>XSL 1.0 Delimited String Tokeniser</title>
</head>
<body>
<xsl:value-of select="food/meta"/>
<div >
<xsl:call-template name="tokenize">
<xsl:with-param name="string" select="food/keywords" />
<xsl:with-param name="delimitr" select="','" />
</xsl:call-template>

</div>
</body>
</html>
</xsl:template>
<xsl:template name="tokenize">
<xsl:param name="string" />
<xsl:param name="delimitr" />
<xsl:choose>
<xsl:when test="contains($string, $delimitr)">
<div style="border:1px solid red;">
<h3><xsl:value-of select="substring-before($string,$delimitr)" /></h3>
<xsl:variable name="data" select="substring-before($string,$delimitr)"/>
</div>
<xsl:call-template name="tokenize">
<xsl:with-param name="string" select="substring-after($string, $delimitr)" /><xsl:with-param name="delimitr" select="$delimitr" /></xsl:call-template>
</xsl:when>
<xsl:otherwise>
<div style="border:1px solid red;">
<h3><xsl:value-of select="$string" /></h3>
</div>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>

Resultant output HTML :-

<div>
<div style="border: 1px solid red;">
<h3>Fruits</h3>
</div>
<div style="border: 1px solid red;">
<h3> Vegetables</h3>
</div>
<div style="border: 1px solid red;">
<h3> Pulses</h3>
</div>
<div style="border: 1px solid red;">
<h3> Meat</h3>
</div>
<div style="border: 1px solid red;">
<h3> Cereals </h3>
</div>
</div>

Needless to say … just change the parameter “delimitr” to the delimiter of your choice


Leave a Reply

 
NDK home | Expressing IT | Expressing Palate | Expressing Penmenship | Expressing Awe | Expressing Myself