Reputation: 5941
I'm looking at an old xsl file and trying to understand the why the original author has defined a number of <xsl:template>
elements as self closing tags containing a match
attribute. In the example below my question would be in regards to <xsl:template match="title" />
:
XML
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
</catalog>
XSL
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="cd">
<p>
<xsl:apply-templates select="title"/>
<xsl:apply-templates select="artist"/>
</p>
</xsl:template>
<xsl:template match="title" />
<xsl:template match="artist">
Artist: <span style="color:#00ff00">
<xsl:value-of select="."/></span>
<br />
</xsl:template>
</xsl:stylesheet>
Since the tags are self-closing, there is obviously no content in the <xsl:template \>
. What's the point of doing this? Is this a technique to "hide" the XML data that associated to the template
via the match attribute?
Upvotes: 2
Views: 677
Reputation: 167516
It doesn't make much sense in that stylesheet that explicitly uses <xsl:apply-templates select="title"/>
to then also use <xsl:template match="title" />
to make sure title
elements produce no output but in case of e.g. <xsl:apply-templates select="*"/>
or simply <xsl:apply-templates/>
in the template of the cd
parent you could then use the empty <xsl:template match="title" />
to make sure title
elements don't produce any output.
In the given stylesheet it would of course be easier to simply remove the <xsl:apply-templates select="title"/>
.
Where it is often used is together with the identity transformation template
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
to which you then add some templates to transform certain elements and you can add empty templates (e.g. <xsl:template match="title" />
) to remove other elements (e.g. title
elements) as that way they don't produce any output.
Upvotes: 0
Reputation: 111521
Self closing xsl:template
tags serve to suppress the matched node. This is commonly used in conjunction with the identity transformation so that everything else is copied to output except the suppressed nodes.
<xsl:template match="title" />
, for example, would do nothing for title
elements matched in the input document.
Upvotes: 2