XSLT » Elements » xsl:element


The xsl:element element is used to create and name an element (node) that can appear in the output. This ability to create both custom elements and attributes, and to display the results, is a major reason why stylesheets generated by XSL are a very sophisticated approach to displaying XML data.

There are two ways to add attributes to a created element: by using the xsl:attribute, xsl:copy, and the xsl:copy-of elements or, by using the optional use-attribute-sets attribute of the xsl:element element. Any attributes created using the use-attribute-sets attribute that have the same name as attributes created using the xsl:attribute, xsl:copy, and the xsl:copy-of elements, will be overwritten.
There is a firm restriction regarding the addition of attributes. After a child node has been added to an element, no additional attributes can be added to the parent node. This rule is required so that the XSL processor does not have to store the result tree in memory. Otherwise, if attributes could be added at a later time, the result tree would have to be stored while the XSL processor searched the entire tree for additional attributes.
Note, you can use the xsl:copy element to copy a node from the source document.
This element is not self-closing. The separate closing element is mandatory.


<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<xsl:for-each select="devguru_staff/programmer">
<xsl:element name="staff_member">
<xsl:attribute name="dob">
<xsl:value-of select="dob" />
<xsl:value-of select="name" />
<br />
<staff_member dob="03/21/1970">Bugs Bunny</staff_member>
<br />
<staff_member dob="08/09/1949">Daisy Duck</staff_member>
<br />
<staff_member dob="04/13/1977">Minnie Mouse</staff_member>
<br />
<staff_member dob="07/04/1979">Pluto</staff_member>
<br />
<staff_member dob="11/30/1956">Porky Pig</staff_member>
<br />
<staff_member dob="01/19/1953">Road Runner</staff_member>
<br />

In this example we create a staff_member element that contains the name of each staff member. This is the code for xslt_example_stylesheet.xsl.
We use the DevGuru Staff List XML file for our example with the following header:
<?xml-stylesheet type="text/xsl" href="xslt_example_element.xsl"?>

Language(s): XSLT

See Also: