<xsl:copy-of>

XSLT Function: <xsl:copy-of>The XSLT <xsl:copy-of> element makes a deep copy of an XML node as defined by an expression in the select attribute.

The expression defined in the mandatory select attribute is either an XPATH expression (for nodes) or a variable reference pointing to a node or node set.

The <xsl:copy-of> elements inserts the node(s) identified by the select attribute into the output document. The function makes a deep copy of the identified node(s) – meaning that the selected nodes are copied; including all the node’s children/descendants, attributes, and namespaces.

Use the <xsl:copy> function if a shallow copy is required; that is – only the node is copied – excluding all children, attributes and descendants.


 

Syntax


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

where expression is either an XPATH expression or an XSLT variable reference.

Attributes

namemandatory/optionaldescription
selectMANDATORYan XPATH expression or variable reference.

Examples

For our examples we are using the fictional library as an input XML. Any XSL transform examples we define uses this XML as an input.

<?xml version="1.0" encoding="UTF-8"?>
<library>
<category name="dogs">
<book>
<name>All about dogs</name>
<author>Someone</author>
<isin>true</isin>
<daysuntilreturn>0</daysuntilreturn>
</book>
</category>
<category name="cats">
<book>
<name>All about cats</name>
<author>Someone</author>
<isin>false</isin>
<daysuntilreturn>3</daysuntilreturn>
</book>
</category>
</library>

How to copy nodes between XML documents

The following XSL transform shows how to copy a node (including its children/descendants and attributes) from the source XML document to the target XML document. The purpose of the transform is to select the cats category and copy it and all its book children to the output XML.

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<myoutput>
<xsl:copy-of select="/*/category[@name=cats]" />
</myoutput>
</xsl:template>
</xsl:stylesheet>

The output XML with copied nodes looks as follows:

<?xml version="1.0" encoding="UTF-8"?>
<myoutput>
<category name="cats">
<book>
<name>All about cats</name>
<author>Someone</author>
<isin>false</isin>
<daysuntilreturn>3</daysuntilreturn>
</book>
</category>
</myoutput>

Posted in XSLT and tagged .

Leave a Reply