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

江枫思渺然 提交于 2020-01-23 05:39:11

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/1859166/what-is-the-difference-between-copy-of-and-apply-templates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!