Is there a way to prevent unmatched xml tags from being displayed using xslt?
Here's a contrived example of an XML document. In my real case, the xml is pretty complex with several nested levels.
<alphabet>
<a>A</a>
<b>B</b>
<c>C</c>
... and so on
</alphabet>
Using xslt I want to transform the document so that only vowels are printed.
In my real case, we are using empty template matching tags to block display. But this is too much for me.
a source to share
I would not allow the "default" or "lowest priority / priority" pattern to silently swallow vowels or do any other meaningful application processing .
The good news is that the template for all otherwise unmatched nodes (of a given type) should give a good debug message and finish processing if necessary.
If this recommendation is not followed, then some errors will be quietly left unnoticed, and it will be very difficult to find and fix them in any fixed period of time.
Here's a solution that only includes one blank template :
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:my="my:my"
>
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<my:vowels>
<c>A</c>
<c>E</c>
<c>I</c>
<c>O</c>
<c>U</c>
</my:vowels>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="c[not(. = document('')/*/my:vowels/*)]"/>
</xsl:stylesheet>
When this transformation is done in the following XML document :
<alphabet>
<c>A</c>
<c>B</c>
<c>C</c>
<c>D</c>
<c>E</c>
<c>F</c>
<c>G</c>
<c>H</c>
<c>I</c>
<c>J</c>
<c>K</c>
<c>L</c>
<c>M</c>
<c>N</c>
<c>O</c>
<c>P</c>
<c>Q</c>
<c>R</c>
<c>S</c>
<c>T</c>
<c>U</c>
<c>V</c>
<c>W</c>
<c>X</c>
<c>Y</c>
<c>Z</c>
</alphabet>
the desired result is obtained :
<alphabet>
<c>A</c>
<c>E</c>
<c>I</c>
<c>O</c>
<c>U</c>
</alphabet>
a source to share
XSLT has precedence rules for templates with conflicting matches (link to XSLT specification). Hence, you can have a * template that "swallows" the default tags and add explicit templates that render or handle vovels.
a source to share