How Does xsl:attribute-set Work in XSLT?

The xsl:attribute-set element in XSLT defines a named, reusable bundle of attributes that can be applied to output elements across a stylesheet. Instead of repeatedly declaring common XML or HTML attributes like classes, styles, identifiers, or XML namespaces on individual elements, developers can declare an attribute set once as a top-level element and reference it across templates. This improves maintainability, reduces boilerplate markup, and enables dynamic attribute generation.

Defining and Using an Attribute Set

An xsl:attribute-set must be declared as a top-level element, which means it appears as a direct child of the <xsl:stylesheet> or <xsl:transform> root. Inside the set, individual attributes are defined using <xsl:attribute> elements.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!-- Declaration of a reusable attribute set -->
  <xsl:attribute-set name="table-formatting">
    <xsl:attribute name="border">1</xsl:attribute>
    <xsl:attribute name="cellpadding">5</xsl:attribute>
    <xsl:attribute name="cellspacing">0</xsl:attribute>
    <xsl:attribute name="class">data-table</xsl:attribute>
  </xsl:attribute-set>

  <!-- Applying the attribute set -->
  <xsl:template match="dataset">
    <table xsl:use-attribute-sets="table-formatting">
      <xsl:apply-templates select="row"/>
    </table>
  </xsl:template>

</xsl:stylesheet>

When the XSLT processor encounters xsl:use-attribute-sets="table-formatting" on a literal result element or use-attribute-sets on an <xsl:element> or <xsl:copy>, it automatically inserts all attributes declared within that named set onto the resulting output element.

Dynamic Values and Conditional Logic

Attribute values within an xsl:attribute-set do not have to be static strings. Because the contents of <xsl:attribute> are evaluated at execution time within the context of the source node currently being processed, they support XPath expressions and conditional blocks.

<xsl:attribute-set name="dynamic-row-style">
  <xsl:attribute name="class">
    <xsl:choose>
      <xsl:when test="position() mod 2 = 0">even-row</xsl:when>
      <xsl:otherwise>odd-row</xsl:otherwise>
    </xsl:choose>
  </xsl:attribute>
  <xsl:attribute name="data-id">
    <xsl:value-of select="@id"/>
  </xsl:attribute>
</xsl:attribute-set>

Every time dynamic-row-style is applied to an element, the processor computes the class and data-id values based on the current context item, generating striped tables or dynamic metadata effortlessly.

Chaining, Inheritance, and Overriding

XSLT provides built-in mechanisms for combining and extending attribute sets:

By centralizing repeated attributes, xsl:attribute-set transforms complex formatting tasks into modular, maintainable rules that behave similarly to CSS classes for XML and HTML transformation pipelines.