tags:

views:

248

answers:

2

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

+5  A: 

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.

Tomalak
+1  A: 

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>
Dimitre Novatchev
Thanks. What is syntax to loop this comma separated parameter? Tried above solution ,but got error "Cannot find the script or external object that implements prefix 'http://fxsl.sf.net/'. "I think I may have not downloaded files properly.Well, I just need to match each id value in this comma separated string parameter against the XML node id and if match found collect each node's text to display in output XML. Please note I have to do this in XSLT 1.0.
contactkx
@contactx: Do you mean that you cannot run my transformation ? Did you download FXSL 1.x? The `href` attribute of the `<xsl:import>` instruction should specify the full or relative path to the template in the library.
Dimitre Novatchev