Handling unexpected children in xsl:apply-templates

When you use xsl:apply-templates in a xsl:template, you might get extra text strings in the transformed results if your input XML data contains unexpected elements with text nodes (due to default XSLT template rules, the extra elements themselves and their attributes are ignored).

There are three ways you can handle this situation:

  • Write an XML schema and validate input data against it before the transformation;
  • List the children you expect in the xsl:apply-templates instruction;
  • Define a low-priority default template the does nothing.
For example, when the input XML document ...
<?xml version="1.0" ?>
<data>
  <a>A1</a>
  <b>B1</b>
  <c>Unexpected</c>
  <b>B2</b>
  <a>A2</a>
</data>
... is processed with the stylesheet ...
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="data">
  <xsl:apply-templates /></xsl:template>

<xsl:template match="a">
  A: <xsl:value-of select="text()" />
</xsl:template>

<xsl:template match="b">
  B: <xsl:value-of select="text()" />
</xsl:template>

</xsl:stylesheet>
... you get the string Unexpected in the transformed results. You could either list the children you expect in the xsl:apply-templates, for example ...
<xsl:template match="data">
  <xsl:apply-templates select="a|b" /></xsl:template>
... or you could define a default template that does nothing (overwriting the built-in default that outputs the child text nodes) ...
<xsl:template match="*" priority="-100" />

This post is part of You've asked for it series of articles.

2 comments:

Jean-Philippe Martin said...

Hi! Thanks, I was really puzzled by some extra characters being output after my xsl:apply-templates call finished. Your explications helped me solve the problem.

Anonymous said...

Your code got me in the right direction. The solution you provide was a bit buggy for me. I found a better solution at: http://stackoverflow.com/questions/346362/how-can-xslapply-templates-match-only-templates-i-have-defined

Thanks for the post!

Post a Comment