Diaboliko
Diaboliko

Reputation: 231

XSLT 1.0: string into array variable

I have a variable as below:

<xsl:variable name="ARRAY">
One,Two,Three,Four
</xsl:variable>

With XSLT 2.0 I used tokenize functions and I set an array variable:

<xsl:variable name="tokenizedSample" select="tokenize($ARRAY,',')"/>

and get array value with:

<xsl:value-of select="$tokenizedSample[1]"/>

Unfortunately I must use XSLT 1.0 and I don't know as replace this situation... I found some examples to create a template as below:

 <xsl:template name="SimpleStringLoop">
    <xsl:param name="input"/>
    <xsl:if test="string-length($input) &gt; 0">
      <xsl:variable name="v" select="substring-before($input, ',')"/>
      <field>
        <xsl:value-of select="$v"/>
      </field>
      <xsl:call-template name="SimpleStringLoop">
        <xsl:with-param name="input" select="substring-after($input, ',')"/>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>

and calling this template as below:

        <xsl:variable name="fields">
              <xsl:call-template name="SimpleStringLoop">
                <xsl:with-param name="input" select="$ARRAY"/>
              </xsl:call-template>
        </xsl:variable>

and accessing to this new array with:

<xsl:value-of select="$fields[1]"/>

but doesn't work.

How can I do?

I would like a XSLT 1.0 variable as array because I want read it with for example:

$newArray[1]

Thanks.

Upvotes: 3

Views: 10561

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117102

I don't see why you would define a variable that needs tokenizing, instead of defining it as "tokenized" to begin with.

In XSLT 1.0, this could be done as:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="http://www.example.com/my"
exclude-result-prefixes="my">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<my:items>
    <item>One</item>
    <item>Two</item>
    <item>Three</item>
    <item>Four</item>
</my:items>

<!-- the rest of the stylesheet -->

</xsl:stylesheet>

With this in place, you can do:

<xsl:value-of select="document('')/xsl:stylesheet/my:items/item[2]"/>

from anywhere in your stylesheet to retrieve "Two".


Of course, you could put the "array" into a variable:

<xsl:variable name="my-items" select="document('')/xsl:stylesheet/my:items/item" />

so that you can shorten the reference to:

<xsl:value-of select="$my-items[2]"/>

Upvotes: 4

Related Questions