XSLT to order attributes

Attribute order is insignificant per the XML Recommendation:

Note that the order of attribute specifications in a start-tag or empty-element tag is not significant.

Therefore, XSLT provides no way to control attribute ordering on output.

Attribute ordering within W3C Recommendations

In general, the XML recommendations will all consider attribute ordering to be insignificant, but see the section on attribute processing in the XML Normalization Recommendation or the Canonical XML Recommendation if your application has a need for attribute ordering. You'd have to do this outside of standard XSLT, however.

Attribute ordering implementational hacks

If you recognize that imposing an ordering on XML attributes is intrinsically flawed, is contrary to interoperability, and is completely outside of both the XML Recommendation and established practices for working with XML, and yet you still must control attribute ordering, here are some ways of implementing such control...

As Michael Kay mentions in another answer to this question, Saxon 9.5 (PE or higher) has an XSLT extension that provides control over the serializer's ordering of attributes. See saxon:attribute-order for details.

You could post-process the XML produced by standard XSLT. Operating beneath the XML library level, you can of course gain full lexical control of attribute ordering via character or string level processing.

You could rely upon implementational details of the ordering provided by an XML library. For example, some libraries will write attributes out in alphabetical order according to the names of the attributes, or will preserve the attribute order provided to them. Obviously, relying upon implementational details is inherently unreliable. That said, it is likely that implementations of, for example, XMLStreamWriter.writeAttribute will continue to honor the order of attributes given to them in the future.

One last reiteration of the real answer to all questions of XML attribute ordering is in order before closing...

Treating XML attributes as having an ordering is contrary to the XML Recommendation and should be avoided.


Saxon 9.5 (PE or higher) provides a serialization option saxon:attribute-order which allows you to control the attribute order generated by the serializer. Although attribute order should not make any difference to any sane receiving application, consistent ordering can improve the human readability of the XML, and since human readability was one of the objectives of XML, I thought this was a reasonable feature to add.