What is the difference between and ?

2019-06-16 20:25发布

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?

标签: xslt
2条回答
Summer. ? 凉城
2楼-- · 2019-06-16 20:56
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.

查看更多
Summer. ? 凉城
3楼-- · 2019-06-16 21:13
  • 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>
查看更多
登录 后发表回答