Previous | Next | Indexes
Zvon > Tutorials > XSLT 2.0 Tutorial > Elements and attributes (5/7) >

Creating attributes with xsl:attribute

Attributes can be created with xsl:attribute instruction. These elements must be the first children of the instruction which creates their parent element in the output.

The name of the created attribute is given by attribute name which can be created with help of curly brackets. Content of xsl:attribute may be used to set value of the new attribute.

XSLT

      <xsl:stylesheet
                  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                  version="2.0">
            <xsl:output  method="xml"
                        indent="yes"
                        omit-xml-declaration="yes"/>

            <xsl:template  match="/*">
                  <xxx>
                        <xsl:attribute  name="r">12</xsl:attribute>
                        <xsl:apply-templates  select="bbb"/>
                  </xxx>
            </xsl:template>

            <xsl:template  match="bbb">
                  <xsl:element  name="{.}">
                        <xsl:attribute  name="a-{position()}">X</xsl:attribute>
                  </xsl:element>
            </xsl:template>

      </xsl:stylesheet>
XML

      <aaa>
            <bbb>x</bbb>
            <bbb>y</bbb>
            <bbb>z</bbb>
      </aaa>
Output

      <xxx  r="12">
            <x  a-1="X"/>
            <y  a-2="X"/>
            <z  a-3="X"/>
      </xxx>


Previous chapter: Conditional Expressions
Next chapter: Groups
Previous page: Creating elements with xsl:element
Next page: Setting value of an attribute created with xsl:attribute