A bit about the stuff I've done


Friday 13 January 2012

Distinct in XSL

So I frequently have a need to do this but I can never remember how, so I figure why not use my shiny new blog and write about it here!

The problem:
  • You have some node list which contains many, many items.
  • You want to group items based on part of their content
  • You want to do it in xsl
Example:
The xml:
<phrases>   <node type="Greeting">Hello</node>   <node type="Farewell">Goodbye</node>   <node type="Greeting">Hi</node>   <node type="Greeting">Howdy</node>   <node type="Farewell">See you later</node> </phrases>
the result:
Greeting Farewell
The solution:
You can use the generate-id() function.
This function is part of xsl so you don't need any funky includes, but it means you can't use it from XPath (e.g. from C#'s SelectNodes() method)

<xsl:if test="generate-id(.) = generate-id(../node[@type=current()/@type])>   <xsl:value-of select="."/> </xsl:if>

And that's it!
Let's break it down

  • generate-id(.)
    Does exactly what you might expect i.e. it generates a unique ID which represents the current node. Calling generate-id on the same node twice will return the same id.
  • ../node[@type=current()/@type]
    This bit gets all the other nodes which have the same value based on the key we are grouping by (in this case

No comments:

Post a Comment