Scott Penrose

XSLT Default Rules

Scott is an expert software developer with over 30 years experience, specialising in education, automation and remote data.

A gotcha on XSLT is the default rules. A good article describing them is here: http://www.dpawson.co.uk/xsl/sect2/defaultrule.html

The short version:

A default template exists to expand all elements

#!XML
<xsl:template match="*">
  <xsl:apply-templates/>
</xsl:template>

That way you can make a template that matches an element and you will get to it.

A default template exists for text

#!XML
<xsl:template match="text()">
  <xsl:value-of select="."/>
</xsl:template>

Which always expands the text elements.

How to avoid

The first one is sensible and you should leave it. But you can change the behaviour by writing your own.

The second, text expansion can be changed in one of two ways:

  • Add your own match that removes the content (See below)
  • Make sure you only use an apply templates for the element you want - the preferred way.

Removing the text node:

#!XML
<xsl:template match="text()" />

  • XSLT