Reputation:
I'm trying to access a specific element in an array depending on the value of the current date in an XML file.
For example, in the XML
<CurrentMonth>5</CurrentMonth>
Then, in the XSLT - this is set as a variable as
<xsl:variable name="current-month">
xsl:value-of select="//CurrentMonth" />
</xsl:variable>
I also have declared an array of the "Month names" as
<xsl:variable name="array" as="element()*">
<Item>Jan</Item>
<Item>Feb</Item>
<Item>Mar</Item>
<Item>Apr</Item>
<Item>May</Item>
<Item>Jun</Item>
<Item>Jul</Item>
<Item>Aug</Item>
<Item>Sept</Item>
<Item>Oct</Item>
<Item>Nov</Item>
<Item>Dec</Item>
</xsl:variable>
Is it possible in XSLT to return the name of the month (e.g. "Jan") by using a variable as an index for the array?
Example :
<xsl:value-of select="$array[$current-month]">
The code above is throwing me
[FATAL]: Error checking type of the expression 'filter-expr(variable-ref(array/result-tree)
Thanks in advance.
Upvotes: 1
Views: 10726
Reputation: 167716
Define the variable as <xsl:variable name="current-month" select="xs:integer(//CurrentMonth)"/>
, then you can use $array[$current-month]
(although you index a sequence and not an array). With your code you need $array[position() = $current-month]
.
A minimal but complete stylesheet that runs fine for me with Saxon 9.6.0.7 HE is
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
version="2.0">
<xsl:variable name="array" as="element()*">
<Item>Jan</Item>
<Item>Feb</Item>
<Item>Mar</Item>
<Item>Apr</Item>
<Item>May</Item>
<Item>Jun</Item>
<Item>Jul</Item>
<Item>Aug</Item>
<Item>Sept</Item>
<Item>Oct</Item>
<Item>Nov</Item>
<Item>Dec</Item>
</xsl:variable>
<xsl:variable name="current-month" select="xs:integer(//CurrentMonth)"/>
<xsl:template match="/">
<xsl:value-of select="$array[$current-month]"/>
</xsl:template>
</xsl:stylesheet>
and outputs May
when run against the input <CurrentMonth>5</CurrentMonth>
.
Upvotes: 0
Reputation: 117140
You have several syntax errors:
<xsl:variable name="current-month">
xsl:value-of select="//CurrentMonth" />
</xsl:variable>
needs to be:
<xsl:variable name="current-month">
<xsl:value-of select="//CurrentMonth" />
</xsl:variable>
or preferably:
<xsl:variable name="current-month" select="//CurrentMonth" />
Next you have:
<xsl:value-of select="$array[$current-month]">
which needs to be closed:
<xsl:value-of select="$array[$current-month]"/>
and, in case you are using the first form of defining the variable, it needs to be:
<xsl:value-of select="$array[number($current-month)]">
Upvotes: 1