XSD Attributes
All attributes are declared as simple types.
What is an attribute?
Simple elements cannot have attributes. If an element has attributes, it is treated as a complex type. However, attributes themselves are always declared as simple types.
How to declare an attribute?
The syntax for defining an attribute is
Here, xxx refers to the attribute name, and yyy specifies the data type of the attribute. XML Schema has many built-in data types.
The most common types are:
- xs:string
- xs:decimal
- xs:integer
- xs:boolean
- xs:date
- xs:time
Example
This is an XML element with an attribute:
This is the corresponding attribute definition:
Default and fixed values for attributes
Attributes can have a specified default value or fixed value.
When no other value is specified, the default value is automatically assigned to the element.
In the following example, the default value is "EN":
A fixed value is also automatically assigned to the element, and you cannot specify another value.
In the following example, the fixed value is "EN":
Optional and required attributes
By default, attributes are optional. To specify that an attribute is required, use the "use" attribute:
Restrictions on content
When an XML element or attribute has a defined data type, restrictions are added to the content of the element or attribute.
If the type of an XML element is "xs:date" and its content is a string like "Hello World", the element will not pass validation.
Through XML Schema, you can also add your own restrictions to your XML elements and attributes. These restrictions are called facets (editor's note: literally the face of a polyhedron, which can be translated as restriction facet). You will learn more about facets in the next section.
Other extensions