Strontium_99
Strontium_99

Reputation: 1803

How to pass as variable into .xslt 1.0 key expressions

Following on from my original question: Filtering, Grouping, Counting and Selecting specific nodes in XML using XSLT 1.0

I've now run into another problem. Using this code that was kindly provided by michael.hor257k

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:key name="vehicle-by-series" match="Vehicle[Model='KA']" use="Series" />

<xsl:template match="/Dealer">
    <xsl:for-each select="Vehicle[Model='KA'][count(. | key('vehicle-by-series', Series)[1]) = 1]">
        <xsl:value-of select="Model"/>
        <xsl:text>: </xsl:text>
        <xsl:value-of select="Series"/>
        <xsl:text>, </xsl:text>
        <xsl:variable name="grp" select="key('vehicle-by-series', Series)" />
        <xsl:value-of select="count($grp)"/>
        <xsl:text> in stock, starting from </xsl:text>
        <xsl:for-each select="$grp">
            <xsl:sort select="Price" data-type="number" order="ascending"/>
            <xsl:if test="position() = 1">
                <xsl:value-of select="Price"/>
            </xsl:if>
        </xsl:for-each>
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

I'm passing in the parameter model:

<xsl:param name="model" />

From an asp.NET URL variable. I want to substitute the currently hardcoded KA for the model parameter. From the searching I've done you can't use parameters or variables in a key expression in XSLT 1.0. And I don't have the option to upgrade to 2.0. Mores the pity.

Would really appreciate some more help please.

Thanks in advance.

Upvotes: 0

Views: 644

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

I would suggest you do:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:param name="model"/>

<xsl:key name="vehicle-by-series" match="Vehicle" use="concat(Model, '|', Series)" />

<xsl:template match="/Dealer">
    <xsl:for-each select="Vehicle[Model=$model][count(. | key('vehicle-by-series', concat(Model, '|', Series))[1]) = 1]">
        <xsl:value-of select="Model"/>
        <xsl:text>: </xsl:text>
        <xsl:value-of select="Series"/>
        <xsl:text>, </xsl:text>
        <xsl:variable name="grp" select="key('vehicle-by-series', concat(Model, '|', Series))" />
        <xsl:value-of select="count($grp)"/>
        <xsl:text> in stock, starting from </xsl:text>
        <xsl:for-each select="$grp">
            <xsl:sort select="Price" data-type="number" order="ascending"/>
            <xsl:if test="position() = 1">
                <xsl:value-of select="Price"/>
            </xsl:if>
        </xsl:for-each>
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions