The xsl:attribute Element: Creating New Attributes

The <xsl:attribute> Element: Creating New Attributes

Just as you can create new elements with <xsl:element> and set the element name and content at run time, you can use the <xsl:attribute> element to do the same for attributes.

This element has two attributes:

  • name (mandatory). The name of the new attribute. Set to an attribute value template returning a QName.

  • namespace (optional). The namespace of the new attribute. Set to a URI.

This element encloses a template body that sets the value of the attribute.

In the following example, Im creating new <PLANET> elements with attributes corresponding to the various planet names , and values taken from the COLOR attribute in the original <PLANET> elements:

Listing 6.7 Using <xsl:attribute>
 <?xml version="1.0"?>  <xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  <xsl:template match="PLANETS">      <HTML>          <HEAD>              <TITLE>                  Planets              </TITLE>          </HEAD>          <BODY>              <xsl:apply-templates select="PLANET"/>          </BODY>      </HTML>  </xsl:template>  <xsl:template match="PLANET">      <PLANET>          <xsl:attribute name="{NAME}">              <xsl:value-of select="@COLOR"/>          </xsl:attribute>      </PLANET>  </xsl:template>  </xsl:stylesheet> 

As you can see in the following results, Ive created new attributes on the fly, using the names of the planets:

 <HTML>      <HEAD>          <TITLE>              Planets          </TITLE>      </HEAD>      <BODY>          <PLANET Mercury="RED">          </PLANET>          <PLANET Venus="WHITE">          </PLANET>          <PLANET Earth="BLUE">          </PLANET>      </BODY>  </HTML> 


Inside XSLT
Inside Xslt
ISBN: B0031W8M4K
EAN: N/A
Year: 2005
Pages: 196

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net