Tuesday, December 21, 2004
XPath select distinct keys generate id...
p2p.wrox.com Forums - Renderering a browser support table
I think for deep understanding of keys and variables it'll be better to refer to Michael Kay's "XSLT Programmer's reference"(it's an excellent source for XSLT in general), or you can look at the W3C's XSLT 1.0 specification: http://www.w3.org/TR/xslt
;
another online snippet on keys: http://saxon.sourceforge.net/saxon6.5.2/xsl-elements.html#xsl:key
I'll try to explain the point concerned with the grouping technique(well known Muenchian method).
The XPath expression
$all-agents[generate-id(.) = generate-id(key('platform', @platform)[1])]
actually selects all such "user-agent" elements, which have distinct "platform" attribute value(and each of those "user-agent" elements is the first one(in document order) in its respective group). Look how it's going on: generate-id(node) function returns a unique id(string) for the parameter-node; key('platform', @platform)
selects all "user-agent" elements having the same value for "platform" attribute as the context node's "platform" attribute; then we select the first one among them(the predicate [1]) and finally we use the function generate-id() to test wheather the context node is the first "representative" of the group or not, and if so, select it. As a result, the XPath above returns "representatives" of groups(each group consists of "user-agent" elements having the same value for the attribute "platform").
For further clarifications see http://www.jenitennison.com/xslt/grouping/muenchian.html
Keys make XPath expression evaluation more effective; they are similar to indexes in relational databases.
quote:
--------------------------------------------------------------------------------
And what if I didn?t use attributes? If I was about to select distinct element based upon their names (local-name)? Would that complicate things?
--------------------------------------------------------------------------------
No, in this concrete situation you'll just need to slightly change the code. When you'll fully understand the concept of "key", it'll be obvious.