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:
<xsl:value-of>extracts only the string value (plain text) of the selected node and its descendants, discarding all XML tags and attributes.<xsl:copy-of>creates a deep copy of the selected node, preserving the node itself, its child elements, attributes, and internal XML structure intact.
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.
- Markup Stripping: Any child elements inside the selected node lose their XML tags.
- Attributes: Attribute tags are omitted; only the string value is extracted if an attribute is directly selected.
- Primary Use Case: When you need to insert plain text into HTML elements, attributes, or text files without carrying over source XML tags.
How xsl:copy-of Works
The <xsl:copy-of> element performs a deep
duplication of the nodes matched by the XPath expression.
- Markup Preservation: All child tags, nested elements, and namespaces remain completely intact.
- Attributes: All attributes belonging to the selected elements are copied into the result tree.
- Primary Use Case: When you want to replicate an entire XML subtree, carry over formatted markup (such as embedded XHTML tags), or pass a node-set directly to the output.
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 |