If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Monday, October 24, 2011

Best practices XSLT

I'm pleased to see that my own findings in programming with XSLT match the ones from Andrew Welch:
  1. don't use xsl:for-each, use xsl:apply-templates
  2. don't use named templates, use xsl:apply-templates with a mode
  3. if a template just contains a choose/when, separate out the branches into individual templates
  4. instead of xsl:value-of use xsl:apply-templates
  5. one large template is bad, lots of specific small templates is good
Regarding (4): xsl:value-of will create a text node in the result tree, xsl:apply-templates will ultimately apply templates on the text node where the default template will kick in and copy it to the result tree... so the effect is the same, however in the latter case you are making it available for overriding.

so for example:

you could do:

or you could do:

both will output the same result.

Now if a requirement comes in to wrap the type in <b>, but only if its 'beer', if you have used apply-templates you can just add the

...and then go home. However if you have use value-of earlier on,
you would need to go and modify that template first to change it to an apply-templates anyway.


  1. This comment has been removed by the author.

  2. Very good piece of advice! With my endless overriding of the default behavior of the DITA OT, I started thinking the same: my own code should be overridable if I don't wanna be late for dinner!

  3. I hadn't really considered doing #4 before, but your example illustrates perfectly how it can really come in handy.

    1. Well Scott,
      even I learn new best practices each day. Actually sharing your code on the mailinglists will have a tremendous impact on improving your own coding style and solution approach.