Share via


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 child elements, 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 at sign (@). The following example extracts the value of the exchange attribute on stock elements and inserts it into the output. For more information 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 preceding 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. Be aware of the following limitations:

  • You cannot add an attribute to an element that already has an attribute of that name.
  • Attributes added with <xsl:attribute> must appear before children are added to the element.

 Last updated on Saturday, April 10, 2004

© 1992-2003 Microsoft Corporation. All rights reserved.