Microsoft XML SDK 2.6 - XSLT Developer's Guide

Accessing and Outputting Attributes

XSLT provides mechanisms for accessing attributes in the source document, and for generating attributes in the result tree. XSLT attempts to be agnostic about whether data should be encoded as attribute values or subelements, and strives to process either with equal ease.

Attributes in the source document can be accessed in a pattern by preceding the attribute name with the @ symbol. Thus the following example extracts the value of the exchange attribute on stock elements and inserts it into the output. For more details about selecting attributes, see XPath.

<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/">
    <HTML>
      <BODY>
        <TABLE BORDER="2">
          <TR>
            <TD>Symbol</TD>
            <TD>Name</TD>
            <TD>Price</TD>
          </TR>
          <xsl:for-each select="portfolio/stock">
            <TR>
              <xsl:attribute name="TITLE"><xsl:value-of select="symbol"/>
                is listed on the <xsl:value-of select="@exchange"/> 
                stock exchange.</xsl:attribute>
              <TD><xsl:value-of select="symbol"/></TD>
              <TD><xsl:value-of select="name"/></TD>
              <TD><xsl:value-of select="price"/></TD>
            </TR>
          </xsl:for-each>
        </TABLE>
      </BODY>
    </HTML>
  </xsl:template>
</xsl:stylesheet>

Attributes can be created in two ways—by placing them on an output element, such as the BORDER='2' attribute above, or by adding them to an element with the <xsl:attribute> element. <xsl:attribute> allows the output attribute's value to be generated from the source data.

The name attribute specifies the name for the output attribute, and the contents of the tag are evaluated to determine its value. In the previous example, a TITLE attribute is added to the <TR> element to display a ToolTip generated by mixing text with element and attribute values from the source document.

Attributes can be added to an element that already has attributes directly specified on it, so you can mix direct specifications and <xsl:attribute> freely. Watch out for these limitations, though:

Try it!   View the sample above by clicking Portfolio at XSLT Developer's Guide Samples. Move the mouse over each row to see the generated ToolTip.

See the XSL version of this sample at XSL Developer's Guide Samples.