Rookie Programmer Aravind
Rookie Programmer Aravind

Reputation: 12154

What is the difference between <copy-of> and <apply-templates>?

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?

Upvotes: 8

Views: 13004

Answers (2)

LorenVS
LorenVS

Reputation: 12857

  • 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>

Upvotes: 12

Tim Ebenezer
Tim Ebenezer

Reputation: 2724

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.

Upvotes: 6

Related Questions