I don't see the difference between xsl:copy
and xsl:copy-of
.
Which one should I use in which situation?
Definition and Usage. The <xsl:copy-of> element creates a copy of the current node. Note: Namespace nodes, child nodes, and attributes of the current node are automatically copied as well! Tip: This element can be used to insert multiple copies of the same node into different places in the output.
XSLT is designed to be used as part of XSL. In addition to XSLT, XSL includes an XML vocabulary for specifying formatting. XSL specifies the styling of an XML document by using XSLT to describe how the document is transformed into another XML document that uses the formatting vocabulary.
Used to construct arbitrary sequences. It may select any sequence of nodes and/or atomic values, and essentially adds these to the result sequence. Category: instruction. Content: sequence-constructor.
In short, xsl:copy
is a shallow copy; xsl:copy-of
is a deep copy.
xsl:copy
vs xsl:copy-of
xsl:copy
when you want to copy just the context item and
have other plans for the children of the context item.xsl:copy-of
when you want to copy XPath-selected nodes and
their children, recursively.
xsl:copy
instruction copies the context item but none
of its children nodes.xsl:copy
instruction cannot have a @select
XPath.A very common use of xsl:copy
can be found in the identity transformation:
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
Notice that here the node itself is copied via xsl:copy
and the children nodes are then transformed via xsl:apply-templates
, giving other templates a chance to intervene in the transformation.
xsl:copy-of
instruction evaluates the XPath in its required @select
attribute and copies the selected nodes and their children nodes, recursively.xsl:copy-of
instruction must have a @select
XPath.Notice that xsl:copy-of
could have been used in the identity transformation, however the flexibility afforded by allowing other templates the chance to match during the recursion would have been lost.
xsl:copy
is a shallow copy. Use it if all you want is to copy the current node (the "context item" in spec-speak).
xsl:copy-of
is a deep copy. Use it if you want to copy the complete node tree under the current node. For a more thorough and complete explanation read the spec that has been linked to from the first comment.
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