Luke Matthews
Luke Matthews

Reputation: 49

passing parameter variable XSLT 1.0

I have something like the following XML: (but with more products)

<?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>
        <name>Mango</name>
        <type>fruit</type>
        <imageurl>pic.jpeg</imageurl>
    </product>
    <product>
        <name>banana</name>
        <type>fruit</type>
        <imageurl>pic3.jpeg</imageurl>
    </product>
    <product>
        <name>duck</name>
        <type>mammal</type>
        <imageurl>pic2.jpeg</imageurl>
    </product>
</products>

And this XSL: (but with more elements and attributes)

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:param name="typeSelected"/>
<xsl:template match="product/{$typeSelected}">
    <xsl:element name="img">
        <xsl:attribute name="class">juice</xsl:attribute>
        <xsl:attribute name="src">
            <xsl:value-of select="imageurl"/>
        </xsl:attribute>
    </xsl:element>
</div>
</xsl:template>

I'm setting the parameter's value with an external JavaScript file but I want to then group only the products who's <type> match the value of that parameter. Obviously the XSL needs changing and having read around I know I can't use parameters in a match statement. It feels like what I attempting shouldn't be too hard. Am I missing something obvious?

Given the parameter fruit I would like the output to be something like:

<img class="juice" src="pic.jpeg"/>
<img class="juice" src="pic3.jpeg"/>

Upvotes: 0

Views: 1085

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117175

I would do it this way:

XSLT 1.0

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

<xsl:param name="typeSelected"/>

<xsl:key name="product-by-type" match="product" use="type" />

<xsl:template match="/">
    <root>
        <xsl:for-each select="key('product-by-type', $typeSelected)">
            <img class="juice" src="{imageurl}"/>
        </xsl:for-each>
    </root>
</xsl:template>

</xsl:stylesheet>

Result (when $typeSelected = "fruit"):

<?xml version="1.0" encoding="utf-8"?>
<root>
   <img class="juice" src="pic.jpeg"/>
   <img class="juice" src="pic3.jpeg"/>
</root>

Note:

  1. An XML document must have a root element;

  2. The content of the class attribute is hard-coded; I don't see it anywhere in your input;

  3. Ducks are not mammals.

Upvotes: 1

Related Questions