Microsoft XML 2.5 SDK


 

Accessing and Outputting Attributes

[This is preliminary documentation and subject to change.]

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:

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.