fedExpress
fedExpress

Reputation: 25

XSLT for-each-group group-by variable

I am trying to achieve a more flexible groub-by statement for my XSLT, using variable (depending of variable value, there is different grouping needed):

.......
    <xsl:param name="rows"/>
    <xsl:variable name="groupBy">
        <xsl:choose>
            <xsl:when test="$report_type='first_type'">
                <xsl:value-of select="concat(date,ccy)"/>
            </xsl:when>
            <xsl:otherwise>
                <xsl:value-of select="concat(type,ccy)"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:variable>
    <xsl:for-each-group select="$rows" group-by="$groupBy">
    .....
    </xsl:for-each-group>

As far as I know this kind of construction won't work (well, it didn't work for me).

My question is: how to pass a variable to the group-by attribute?

Thank you in advance for any kind of help.

Upvotes: 0

Views: 2046

Answers (2)

michael.hor257k
michael.hor257k

Reputation: 117100

The problem here is not "how to pass a variable to the group-by attribute", but what is the content of the passed variable. The group-by attribute must contain an XPath expression - you are passing it a string value.

If there are only two ways to group the nodes, I would suggest you use the following construct:

<xsl:for-each-group select="item" group-by="if($report_type='first_type') then concat(date,ccy) else concat(type,ccy)">

Upvotes: 3

Michael Kay
Michael Kay

Reputation: 163585

Yes, the group-by expression can be a variable reference, but then it will have the same value for every item in the population, so that's pretty pointless. It's a bit like saying group-by="42".

In general if the computation of the grouping key is too complex to go inline in the group-by attribute, the best solution is to put it in a function, which you can then call as group-by="my:grouping-key(.)".

I'm not convinced that's the case here. You could write this, for example, as

group-by="concat(if ($report_type='first_type') then date else type, ccy)"

Upvotes: 3

Related Questions