Saturday, October 07, 2017

Splitting a string using XSLT 2.0

The tokenize function available in XSL Transformations (XSLT) Version 2.0 allows you to split a string on any separator that matches a given regular expression.

The example below shows how you can split a comma-delimited string:

Input XML:

<data>
  <stringToSplit>foo,bar,baz</stringToSplit>
</data>

XSL 2.0 Stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="data">
    <items>
      <xsl:variable name="stringToSplit" select="stringToSplit" />
      <xsl:for-each select="tokenize($stringToSplit, ',')">
        <item>
          <xsl:value-of select="." />
        </item>
      </xsl:for-each>
    </items>
  </xsl:template>
</xsl:stylesheet>

Output XML:

<?xml version="1.0" encoding="UTF-8"?>
<items>
  <item>foo</item>
  <item>bar</item>
  <item>baz</item>
</items>

No comments:

Post a Comment