Difference Between xsl:value-of and xsl:copy-of

When transforming XML documents using XSLT, understanding how to extract and output data correctly is essential. This article explains the fundamental differences between the <xsl:value-of> and <xsl:copy-of> elements, demonstrating how each instruction handles XML nodes, child elements, and attributes so you can choose the correct element for your transformation.

Key Difference at a Glance

The primary difference between <xsl:value-of> and <xsl:copy-of> lies in how they handle XML markup:


How xsl:value-of Works

The <xsl:value-of> element evaluates an XPath expression, converts the result into a string, and outputs only the textual content.


How xsl:copy-of Works

The <xsl:copy-of> element performs a deep duplication of the nodes matched by the XPath expression.


Practical Example

Consider the following source XML snippet:

<product id="101">
    <description>Heavy-duty <b>steel</b> wrench</description>
</product>

Applying xsl:value-of

<xsl:value-of select="product/description"/>

Output:

Heavy-duty steel wrench

Note: The <b> and </b> tags are completely stripped away.

Applying xsl:copy-of

<xsl:copy-of select="product/description"/>

Output:

<description>Heavy-duty <b>steel</b> wrench</description>

Note: The entire element structure, including the <description> and <b> tags, is preserved.


Summary Comparison

Feature xsl:value-of xsl:copy-of
Output Type Plain string Node-set / Subtree
Child Tags Stripped Retained
Attributes Ignored (unless directly targeted) Retained with their elements
Operation Type Shallow string conversion Deep copy
Common Target Text fields, HTML text Structured XML/HTML subtrees