Copying Nodes

Contact Us or call 1-877-932-8228
Copying Nodes

Copying Nodes

Sometimes you find that there is a chunk of code from the source XML document that you want to leave exactly as is in the output. There are two tags that make this very easy to do in XSLT: xsl:copy and xsl:copy-of.

xsl:copy

The xsl:copy element is used to copy the element name from the source document. The following example illustrates how it is used.

Code Sample:

AdvancedXsltTechniques/Demos/BeatlesCopy.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
				xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="xml" indent="yes"/>
	<xsl:template match="/beatles">
		<xsl:copy>
			<xsl:apply-templates select="//name"/>
		</xsl:copy>
	</xsl:template>
	<xsl:template match="name">
		<xsl:copy>
			<xsl:value-of select="lastname"/>, <xsl:value-of select="firstname"/>
		</xsl:copy>
	</xsl:template>
</xsl:stylesheet>

The first xsl:copy outputs a beatles node and the second xsl:copy outputs a name node for each name node in the source document. When AdvancedXsltTechniques/Demos/BeatlesCopy.xml is transformed against AdvancedXsltTechniques/Demos/BeatlesCopy.xsl, the output looks like this.

Code Sample:

AdvancedXsltTechniques/Demos/BeatlesCopyOutput.xml
<?xml version="1.0" encoding="UTF-8"?>
<beatles>
	<name>McCartney, Paul</name>
	<name>Lennon, John</name>
	<name>Harrison, George</name>
	<name>Starr, Ringo</name>
	<name>Dunn, Nat</name>
</beatles>

xsl:copy-of

The xsl:copy-of element is used to make a deep copy from the source document, including all attributes and descendant elements. The following example illustrates how it is used.

Code Sample:

AdvancedXsltTechniques/Demos/BeatlesCopyOf.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" 
				xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
	<xsl:output method="xml" indent="yes"/>
	<xsl:template match="/beatles">
		<xsl:copy>
			<xsl:apply-templates select="//name"/>
		</xsl:copy>
	</xsl:template>
	<xsl:template match="name">
		<xsl:copy-of select="."/>
	</xsl:template>
</xsl:stylesheet>

The xsl:copy-of outputs a deep copy of a name node for each name node in the source document. When AdvancedXsltTechniques/Demos/BeatlesCopyOf.xml is transformed against AdvancedXsltTechniques/Demos/BeatlesCopyOf.xsl, the output looks like this.

Code Sample:

AdvancedXsltTechniques/Demos/BeatleCopyOfOutput.xml
<?xml version="1.0" encoding="UTF-8"?>
<beatles>
	<name>
		<firstname>Paul</firstname>
		<lastname>McCartney</lastname>
	</name>
	<name>
		<firstname>John</firstname>
		<lastname>Lennon</lastname>
	</name>
	<name>
		<firstname>George</firstname>
		<lastname>Harrison</lastname>
	</name>
	<name>
		<firstname>Ringo</firstname>
		<lastname>Starr</lastname>
	</name>
	<name>
		<firstname>Nat</firstname>
		<lastname>Dunn</lastname>
	</name>
</beatles>
Next