XSD Attribute
All attributes are declared as simple types.
What is an Attribute?
A simple element cannot have attributes. If an element has attributes, it is considered 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 commonly used types are:
- xs:string
- xs:decimal
- xs:integer
- xs:boolean
- xs:date
- xs:time
Example
Here is an XML element with an attribute:
Here is the corresponding attribute definition:
Default and Fixed Values for Attributes
Attributes can have specified default or fixed values.
The default value is automatically assigned to the element when no other value is specified.
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 an attribute as required, use the "use" attribute:
Constraints on Content
When an XML element or attribute has a defined data type, constraints are added to the content of the element or attribute.
If the type of an XML element is "xs:date" and it contains a string like "Hello World", the element will not validate.
Through XML schema, you can also add your own constraints to your XML elements and attributes. These constraints are called facets. You will learn more about facets in the next section.