Click to return to the XML (Extensible Markup Language) home page    
Authoring Well-Formed HTM...     Sorting XML     Getting Started with XSL    
Web Workshop  |  XML (Extensible Markup Language)

Accessing and Outputting Attributes


XSL provides mechanisms for accessing attributes in the source document, and for generating attributes in the result tree. XSL 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 XSL Patterns by preceding the attribute name with the @ symbol. Thus the example below extracts the value of the "exchange" attribute on stock elements and inserts it into the output. For more details on selecting attributes, see XSL Patterns.

<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
  <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>

XSL can create attributes 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 pervious 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! You can view the sample above by clicking Portfolio Sample (Attributes). Move the mouse over each row to see the generated ToolTip.

Download Download this sample.



Back to topBack to top

Did you find this topic useful? Suggestions for other topics? Write us!

© 1999 Microsoft Corporation. All rights reserved. Terms of use.