XML Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 4.00

"copy" - Copy Elements from Source to Result

This section provides a tutorial example on how to generate transformation output in XML format. The third approach is to copy elements using XSLT 'copy' elements in the transformation template to copy element from the source XML document to the result document.

The third way to generate output XML elements is to use "copy" elements to copy elements from the source XML document to the output document.

"copy": A child element used in the content of a "template" element. A "copy" element serves an output statement, which will be evaluated to copy the current element into the result document without its attributes and content.

The syntax of the "copy" element is shown in 2 examples below:

<copy/>

<copy>
 content
</copy>

where "content" is optional. If provided, "content" should be a list of "apply-templates" elements.

Let's see an example of using "copy" elements to copy element from the source XML document to the result document.

Here is the source XML document, output_xml.xml:

<?xml version="1.0"?>
<user name="Herong">
 <role>administrator</role>
 Administrator can delete users.
 <point>100</point>
 Points are earned by posting messages.
</user>

Here is the transformation template that copies some elements from the source XML document:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<xsl:template match="user">
 <xsl:copy>
  <xsl:apply-templates select="role"/>
  <xsl:apply-templates select="point"/>
 </xsl:copy>
</xsl:template>
<xsl:template match="role">
 <xsl:copy/>
</xsl:template>
<xsl:template match="point">
 <xsl:copy/>
</xsl:template>
</xsl:stylesheet>

Run XSLTransformer.java to perform the transformation, you should get:

<?xml version="1.0" encoding="UTF-8" ?> 
<user>
 <role /> 
 <point /> 
</user>

The output looks good. All 3 XML elements are copy in the result XML document correctly. But only element names are copied over. Attributes and text contents are not copied.

Sections in This Chapter

"output" - The Output Format Control Element

Generating Transformation Output in XML Format

"element" and "attribute" - Constructing Output Elements

"copy" - Copy Elements from Source to Result

Copying Attributes and Texts

Dr. Herong Yang, updated in 2009
"copy" - Copy Elements from Source to Result