When should I use <copy-of>
instead of <apply-templates>
?
What is their unique role? Most of the time replacing <apply-templates>
with <copy-of>
gives out weird output. Why is that?
The <xsl:apply-templates> element applies a template to the current element or to the current element's child nodes. If we add a "select" attribute to the <xsl:apply-templates> element, it will process only the child elements that matches the value of the attribute.
With <xsl:apply-templates> the current node moves on with every iteration, whereas <xsl:call-template> does not change the current node. I.e. the . within a called template refers to the same node as the .
mode. The mode attribute allows an element as specified by its Qualified Names to be processed multiple times, each time producing a different result. If <xsl:template> does not have a match attribute, it cannot have a mode attribute.
Definition and Usage. The <xsl:copy> element creates a copy of the current node. Note: Namespace nodes of the current node are automatically copied as well, but child nodes and attributes of the current node are not automatically copied!
xsl:copy-of
is an exact copy of the matched input xml element. No xslt processing takes place and the output from that element will be exactly the same as the input.
xsl:apply-templates
tells the xslt engine to process templates that match the selected elements. xsl:apply-templates
is what gives xslt its overriding capability, since the templates you create with match on elements can have different priorities, and the template with the highest priority will be executed.
Input:
<a>
<b>asdf</b>
<b title="asdf">asdf</b>
</a>
Xslt 1:
<xsl:stylesheet ... >
<xsl:template match="a">
<xsl:copy-of select="b" />
</xsl:template>
</xsl:stylesheet>
Xml output 1:
<b>asdf</b>
<b title="asdf">asdf</b>
Xslt 2:
<xsl:stylesheet ... >
<xsl:template match="a">
<xsl:apply-templates select="b" />
</xsl:template>
<xsl:template match="b" priority="0">
<b><xsl:value-of select="." /></b>
<c><xsl:value-of select="." /></c>
</xsl:template>
<xsl:template match="b[@title='asdf']" priority="1">
<b title="{@title}"><xsl:value-of select="@title" /></b>
</xsl:template>
</xsl:stylesheet>
Xml output 2:
<b>asdf</b>
<c>asdf</c>
<b title="asdf">asdf</b>
copy-of
will simply return you a dump of the XML in the supplied node-set
apply-templates
on the other hand will apply any templates applicable to the node-set passed it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With