The <xsl:element> is used to create new element in XML document. This function is useful when an element’s name is determined at runtime.

Syntax for <xsl:element>

<xsl:element name=”elementName” namespace=”URI” use-attribute-sets=”attributeList”>

<!—Template content -->

</xsl:element>

Where:

  • name is the name of the element to be created. It is mandatory field.
  • namespace is the namespace URI of the element. It is optional.
  • use-attribute-sets is the attribute sets of the elements separated by white space. It is optional.

Below given example has items for sale, their cost price and selling price. XSLT is used to create another document which takes the item name from this document and include profit on each item. The profit item is added using <xsl:element>

Example of how to use <xsl:element>

ElementAdd.xml

<?xml version = "1.0" encoding = "UTF-8"?>

<factory>

    <item>

        <name>Toy</name>

        <buyingPrice>6</buyingPrice>

        <sellingPrice>10</sellingPrice>

    </item>

 

    <item>

        <name>Box</name>

        <buyingPrice>4</buyingPrice>

        <sellingPrice>8</sellingPrice>

    </item>

 

    <item>

        <name>Bag</name>

        <buyingPrice>60</buyingPrice>

        <sellingPrice>100</sellingPrice>

    </item>

</factory>

ElementAdd.xsl

<?xml version = "1.0" encoding = "UTF-8"?>

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

<xsl:template match = "/factory">

      <item>

         <xsl:apply-templates select = "item"/>

      </item>

</xsl:template>

<xsl:template match = "item">

       <xsl:text>&#10;</xsl:text>

       <name>

      <xsl:value-of select="name"/>

       </name>

      <xsl:element name = "profit">

       <xsl:value-of select="(sellingPrice -buyingPrice)"/>      

      </xsl:element>

      <xsl:text>&#10;</xsl:text>

</xsl:template>

</xsl:stylesheet>

Output.xml

<?xml version="1.0"?>

<item>

<name>Toy</name><profit>4</profit>

<name>Box</name><profit>14</profit>

<name>Bag</name><profit>40</profit>

</item>

 

›› go to examples ››