Nichole R
Nichole R

Reputation: 1

Array with XSLT 1.0

I have a simple array below

<xsl:template match="/">
    <xsl:variable name="array">
        <Item>One</Item>
        <Item>Two</Item>
        <Item>Three</Item>
    </xsl:variable>
    <html>
        <body>
            <xsl:value-of select="$array"/>
        </body>
    </html>
</xsl:template> 

Which displays

OneTwoThree

However, when I try

<xsl:value-of select="$array[0]"/>

The entire page breaks

Any idea how I can access "One" in my array?

Upvotes: 0

Views: 1455

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116959

First, there are no arrays in XSLT 1.0. Your variable is a result tree fragment with 3 Item child elements.

Result tree fragments cannot be parsed directly; you need to convert them to a node-set first, using an extension function supported by your processor - for example:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <xsl:variable name="array">
        <Item>One</Item>
        <Item>Two</Item>
        <Item>Three</Item>
    </xsl:variable>
    <html>
        <body>
            <xsl:value-of select="exsl:node-set($array)/Item[1]"/>
        </body>
    </html>
</xsl:template> 

</xsl:stylesheet>

Alternatively, you could bypass the limitation by parsing the stylesheet directly:

<xsl:template match="/">
    <xsl:variable name="array">
        <Item>One</Item>
        <Item>Two</Item>
        <Item>Three</Item>
    </xsl:variable>
    <html>
        <body>
            <xsl:value-of select="document('')//xsl:variable[@name='array']/Item[1]"/>
        </body>
    </html>
</xsl:template> 

Do note that node numbering starts at 1, not 0.

Upvotes: 1

Related Questions