Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma separated string parsing XSLT

Tags:

xslt

How can I loop through a Comma separated string which I am passing as a parameter in XSLT 1.0? Ex-

<xsl:param name="UID">1,4,7,9</xsl:param>

I need to loop the above UID parameter and collectd nodes from within each of the UID in my XML File

like image 202
contactkx Avatar asked May 17 '10 14:05

contactkx


2 Answers

Vanilla XSLT 1.0 can solve this problem by recursion.

<xsl:template name="split">
  <xsl:param name="list"      select="''" />
  <xsl:param name="separator" select="','" />

  <xsl:if test="not($list = '' or $separator = '')">
    <xsl:variable name="head" select="substring-before(concat($list, $separator), $separator)" />
    <xsl:variable name="tail" select="substring-after($list, $separator)" />

    <!-- insert payload function here -->

    <xsl:call-template name="split">
      <xsl:with-param name="list"      select="$tail" />
      <xsl:with-param name="separator" select="$separator" />
    </xsl:call-template>
  </xsl:if>
</xsl:template>

There are pre-built extension libraries that can do string tokenization (EXSLT has a template for that, for example), but I doubt that this is really necessary here.

like image 128
Tomalak Avatar answered Nov 06 '22 08:11

Tomalak


Here is an XSLT 1.0 solution using the str-split-to-words template of FXSL.

Note that this template allows to split on multiple delimiters (passed as a separate parameter string), so even 1,4 7;9 will be split without any problems using this solution.

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:ext="http://exslt.org/common"
>

   <xsl:import href="strSplit-to-Words.xsl"/>

   <xsl:output indent="yes" omit-xml-declaration="yes"/>

    <xsl:template match="/">
      <xsl:call-template name="str-split-to-words">
        <xsl:with-param name="pStr" select="/"/>
        <xsl:with-param name="pDelimiters"
                        select="', ;&#9;&#10;&#13;'"/>
      </xsl:call-template>
    </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the following XML document:

<x>1,4,7,9</x>

the wanted, correct result is produced:

<word>1</word>
<word>4</word>
<word>7</word>
<word>9</word>
like image 4
Dimitre Novatchev Avatar answered Nov 06 '22 08:11

Dimitre Novatchev