Search code examples
xsltxpathxslt-1.0xslt-grouping

Is the [1] in Muenchian grouping really necessary?


Having answered a large number of XSLT questions here on Stack Overflow, I am more than familiar with the Muenchian grouping technique for grouping nodes during an XSL transformation.

The expression used therein is usually something like this:

*[generate-id() =
  generate-id(key('kSomeKey', .)[1])]

It almost invariably contains that [1], but this has always struck me as odd.

The XSLT 1.0 spec defines generate-id() as follows:

The generate-id function returns a string that uniquely identifies the node in the argument node-set that is first in document order.

(emphasis added)

It clearly states that the function operates on the first node in document order, and in this context, the [1] would be selecting the first node in the set in document order, so it seems that the [1] is redundant.

This [1] is used so widely that I am hesitant to omit it, but it seems extraneous. Can anyone clear this up for me?


Solution

  • Semantically the [1] is not necessary but depending on the (lack of) optimization in the XSLT processor it might be more efficient to have it. It will depend on the internals of each XSLT processor whether key('key-name', foo)[1] only computes one node or first computes a node-set with all nodes selected by the key and then takes the first as much as it depends on the XSLT processor to recognize generate-id(key('key-name', foo)) as an expression where only the first node in the node-set computed by the key is needed.