Understanding attributeFormDefault in XML Schema
The attributeFormDefault attribute in an XML Schema
Definition (XSD) specifies whether locally declared attributes in an XML
document must be explicitly qualified with a namespace prefix or remain
unqualified. By establishing a schema-wide default, it simplifies XML
document authoring and dictates how attribute names are bound to the
schema’s target namespace.
The Role of attributeFormDefault
In an XML Schema, the <xs:schema> root element can
define attributeFormDefault with one of two values:
"unqualified" or "qualified".
unqualified(Default): Local attributes in an instance XML document must appear without a namespace prefix. They belong to no namespace, even if the parent element belongs to a target namespace.qualified: Local attributes in an instance XML document must be explicitly associated with the target namespace, typically by using a defined namespace prefix (e.g.,prefix:attributeName).
If the attributeFormDefault attribute is omitted from
the <xs:schema> declaration, the XSD specification
defaults to "unqualified". This behavior differs from
elements, but it is standard practice in XML design because attributes
inherently derive context from the element to which they belong.
Local vs. Global Attributes
The attributeFormDefault setting strictly applies to
local attributes—attributes declared inside an
<xs:complexType> or <xs:element>
definition.
Global attributes—attributes declared directly under
the root <xs:schema> element—are always qualified in
XML instance documents regardless of the
attributeFormDefault setting. Global attributes must always
carry a namespace prefix in the instance document to indicate their
target namespace.
Overriding the
Default with the form Attribute
Individual local attributes can override the schema-wide
attributeFormDefault setting using the form
attribute on the <xs:attribute> declaration.
- Setting
form="qualified"on a local attribute forces that specific attribute to use a namespace prefix in the XML instance, even ifattributeFormDefault="unqualified". - Setting
form="unqualified"on a local attribute ensures that specific attribute requires no prefix, even ifattributeFormDefault="qualified".
Comparison Example
Consider an XSD with a
targetNamespace="http://example.com/ns":
When attributeFormDefault="unqualified":
<ex:item xmlns:ex="http://example.com/ns" id="123" />The id attribute has no prefix and is unqualified.
When attributeFormDefault="qualified":
<ex:item xmlns:ex="http://example.com/ns" ex:id="123" />The id attribute requires the ex: prefix to
associate it with the http://example.com/ns namespace.