SEARCH :
This SectionSite Wide
 

Ektron's Developer Group Blog

A blog for Ektron users, by Ektron Developers

Difference between xsl:value-of and xsl:copy-of and when to use node()

(XML, XSLT) Permanent link   All Posts

When authoring an XSL transform, the difference between xsl:value-of and xsl:copy-of can have a profound and unexpected effect on the results. Once you are aware of the difference, however, it is very easy to know which to use.

In short,

xsl:value-of returns all the TEXT within the selected tag(s).

xsl:copy-of returns all the ELEMENTS (both tags and text) of the selected tag(s).

(Do not confuse xsl:copy-of with xsl:copy. xsl:copy returns just the tag of the context element. xsl:copy does not have a 'select' attribute. It is typically used to pass through an existing XML tag but not its attributes.)

To illustrate the difference between xsl:value-of and xsl:copy-of, refer to this small XML document.

<Name>
 <Family>Smith</Family>
 <Given>John</Given>
</Name>

Following is an XSLT showing various uses of value-of and copy-of with the results of each section shown in the column to the right.

XSLT  Result   Comments

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml" omit-xml-declaration="yes"/>

<xsl:template match="/">

 

   
<xsl:text>
xsl:value-of select="Name"
</xsl:text>
<xsl:value-of select="Name"/>

 xsl:value-of select="Name"

 Smith
 John

xsl:value-of returns all the text within the selected element and its children.
<xsl:text>
xsl:copy-of select="Name"
</xsl:text>
<xsl:copy-of select="Name"/>
 xsl:copy-of select="Name"
<Name>
 <Family>Smith</Family>
 <Given>John</Given>
</Name>
xsl:copy-of returns the selected element (including its tags) and its children (including their tags).

<xsl:text>
xsl:copy-of select="Name/node()"
</xsl:text>
<xsl:copy-of select="Name/node()"/>

 xsl:copy-of select="Name/node()"

 <Family>Smith</Family>
 <Given>John</Given>

Use node() to exclude the tags of the selected element and return just the child elements of the selected element.
<xsl:text>
xsl:copy-of select="Name/text()"
</xsl:text>
<xsl:copy-of select="Name/text()"/>

 xsl:copy-of select="Name/text()"

 
 

Use text() to return the immediate child text and exclude the text of child elements. In this case, the immediate text nodes are white space. To ignore white space between tags, add <xsl:strip-space elements="*"/> to the xsl:template element near the top of your XSLT.

 

</xsl:template>

</xsl:stylesheet>