Re: [xsl] How to use arrays in xsl

Subject: Re: [xsl] How to use arrays in xsl
From: Abel Braaksma Online <>
Date: Tue, 09 May 2006 09:22:08 +0200
Jitendra Kharche wrote:

Hi all, I am facing a problem while writing an xsl. In my xml I have a comma separated values (csv) list. On each of the value in this list I want to do some processing. For that I want to parse the csv string and store it into an array and pass the array to a separate template from processing. Can we do this in xsl?

Jitendra Kharche
Geometric Software Solutions Co. Ltd.
Work: +91-20-2290 6351

Hi Jitendra,

XSLT works with node trees, which you may view as something as a hierarchical array. An element on the same node level can be accessed using [] syntax, like in languages such as C and Java. And you can "loop" like in those languages using the for-each construct. But XSLT is not like those languages. XSLT is a declarative language and comes closer to Lisp than to imparative languages like C, Java, Ruby, VB etc.

What comes close to your problem I think is this (XSLT 2.0):

<xsl:variable name="csv-contents" >
<!-- loop through the lines of the CSV file (replace unparsed-text function with your CSV string or text-node) -->
<xsl:for-each select="tokenize(unparsed-text('some_csv_file.txt', 'UTF-8'), '\n|\r')">
<!-- loop through the cells of the current line -->
<xsl:for-each select="tokenize(., ';')" >
<cell><xsl:value-of select="normalize-space(.)"/></cell>

You can now use this variable $csv-contents as a tree anywhere you like (it's your "array" of nodes, pass it on to your "separate template", included or otherwise). In XSLT 1.0 you cannot do such a thing (you cannot built a temporary tree and use it again and you cannot use tokenize). But as Mukul Gandhi pointed out, there are solutions around. I suggest chapter 2.9 of the XSLT Cookbook (O'Reilly), it worked for me.


Current Thread