xsl:element

  1. element_1-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <product>
  5.     <name>Delta</name>
  6.     <stock>4</stock>
  7.   </product>
  8. </products>
  1. element_1-stylesheet.xsl

  2. <?xml version="1.0"?>
  3. <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  4.   <xsl:output indent="yes"/>
  5.   <xsl:template match="/">
  6.     <xsl:element name="Products">
  7.       <xsl:element name="Product">
  8.         <xsl:element name="Name">
  9.           <xsl:value-of select="products/product/name"/>
  10.         </xsl:element>
  11.         <xsl:element name="Stock">
  12.           <xsl:value-of select="products/product/stock"/>
  13.         </xsl:element>        
  14.       </xsl:element>
  15.     </xsl:element>
  16.   </xsl:template>
  17. </xsl:stylesheet>
  1. element_1-output.xml

  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <Products>
  4.   <Product>
  5.     <Name>Delta</Name>
  6.     <Stock>4</Stock>
  7.   </Product>
  8. </Products>

Comment

Literal constructors to create elements and attributes in output are by far the most common because they are easy to understand at a glance. In this example xsl:element is used to create elements in output. So far we have just hand coded the element names but this more "formal" way of constructing output can be necessary if we want to compute the element name, e.g. based on the input names.

Updated 2009-03-19