XSD Attribute
- Previous Page XSD Elements
- Next Page XSD Facets
All attributes are declared as simple types.
What are attributes?
Simple elements 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 attributes is:
<xs:attribute name="xxx" type="yyy"/>
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
This is an XML element with attributes:
<lastname lang="EN">Smith</lastname>
This is the corresponding attribute definition:
<xs:attribute name="lang" type="xs:string"/>
Default values and fixed values of attributes
Attributes can have specified default values or fixed values.
When no other value is specified, the default value is automatically assigned to the element.
In the following example, the default value is "EN":
<xs:attribute name="lang" type="xs:string" default="EN"/>
Fixed values are also automatically assigned to elements, and you cannot specify another value.
In the following example, the fixed value is "EN":
<xs:attribute name="lang" type="xs:string" fixed="EN"/>
Optional and required attributes
By default, attributes are optional. To specify that an attribute is required, use the "use" attribute:
<xs:attribute name="lang" type="xs:string" use="required"/>
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 the content it contains is a string similar to "Hello World", the element will not validate.
Through XML schema, you can also add your own restrictions to your XML elements and attributes. These restrictions are called facets (editor's note: meaning the face of a polyhedron, which can be translated as facet). You will learn more about facets in the next section.
- Previous Page XSD Elements
- Next Page XSD Facets