XSLT » Elements » xsl:copy-of

Syntax:
<xsl:copy-of
  select="expression"
/>

The xsl:copy-of element inserts a duplicate copy of a node set or tree fragment into the output. Perhaps the most important aspect of this element is that it allows you to insert multiple copies of the same set of nodes into different places in the output. For example, you may wish to repeat a page header.

When a node set is copied, the nodes will be copied into the output in their order of occurrence in the source (this is referred to as document order). Each node and all associated attribute nodes, namespace nodes, children and descendants are copied. In other words, it is a complete, unabridged copy of the set.
 
When a root node is copied, all of the children and descendants are copied, but not the root node itself since there can only be one root.
 
When a tree fragment is copied, it is copied exactly to the output.
 
For all other circumstances, the xsl:copy-of element behaves exactly like the xsl:value-of element. The value being copied is converted into a string for display in the output.
 
In contrast, the xsl:copy element copies the current node in the source document to the output. The copy has the same name, namespace, and type as the original node, but any attributes, children, and other descendants are not copied.
 
This is a self-closing element and it cannot contain any child elements or any content.

Examples

Code:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:variable name="staff_table">
<tr>
<td><b>Name</b></td>
<td><b>Age</b></td>
</tr>
</xsl:variable>
<xsl:template match="/">
<html>
<body>
<table>
<xsl:copy-of select="$staff_table" />
<xsl:for-each select="devguru_staff/programmer">
<tr>
<xsl:if test="age &lt; 35">
<td><xsl:value-of select="name" /></td>
<td><xsl:value-of select="age" /></td>
</xsl:if>
</tr>
</xsl:for-each>
</table>
<p />
<table>
<xsl:copy-of select="$staff_table" />
<xsl:for-each select="devguru_staff/programmer">
<tr>
<xsl:if test="age &gt; 34">
<td><xsl:value-of select="name" /></td>
<td><xsl:value-of select="age" /></td>
</xsl:if>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Output:
NameAge
Bugs Bunny 31
Minnie Mouse 24
Pluto 21

NameAge
Daisy Duck 51
Porky Pig 44
Road Runner 48
Explanation:

In this example, we repeat the table header in two different tables. This is the code for xslt_example_copyof.xsl.
 
We use the DevGuru Staff List XML file for our example with the following header:
<?xml-stylesheet type="text/xsl" href="xslt_example_copyof.xsl"?>

Language(s): XSLT

See Also: