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.
<?xml version="1.0" ?>... is processed with the stylesheet ...
<data>
<a>A1</a>
<b>B1</b>
<c>Unexpected</c>
<b>B2</b>
<a>A2</a>
</data>
<?xml version="1.0" ?>... 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: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>
<xsl:template match="data">... or you could define a default template that does nothing (overwriting the built-in default that outputs the child text nodes) ...
<xsl:apply-templates select="a|b" /></xsl:template>
<xsl:template match="*" priority="-100" />
This post is part of You've asked for it series of articles.
2 comments:
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.
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