Let's say we have a key definition <xsl:key name="contacts-by-surname" match="contact" use="surname"/>
, then the expression key('contacts-by-surname', 'Doe')
gives you a node set with all contact
elements where the surname
is Doe
. The expression key('contacts-by-surname', 'Doe')[1]
gives you the first contact
in that "group".
Now when processing all contact
elements with for-each
or apply-templates
we usually want a way to identify the first contact
element in each group. This can be achieved with <xsl:for-each select="contact[count(. | key('contacts-by-surname', surname)[1]) = 1]">
or <xsl:for-each select="contact[generate-id() = generate-id(key('contacts-by-surname', surname)[1])]">
.
If your requirement is different and you for instance wanted to identify the last item in each group then you could of course use a different predicate, as in <xsl:for-each select="contact[count(. | key('contacts-by-surname', surname)[last()]) = 1]">
or <xsl:for-each select="contact[generate-id() = generate-id(key('contacts-by-surname', surname)[last()])]">
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…