XSD Attributes

The XSD attributes are invariably declared as simple types.

What is an Attribute?

An element is considered to be of a complex type if it has attributes, which simply means that the simple elements cannot have attributes. But when it comes about the declaration of an attribute, it is always a simple type.

How to Define an Attribute?

Syntax: Defining an attribute:

<xs:attribute name="xxx" type="yyy"></xs:attribute>

Here, the name of the attribute is specified by xxx and the data type of the attribute is specified by yyy.

XML Schema built-in data types:

The most common built-in data types of XML Schema are:

• xs: D:string
• xs:decimal
• xs:integer
• xs:boolean
• xs:date
• xs:time

Example:

XML element with an attribute:

<firstname lang="EN">Tom</firstname>

Corresponding attribute definition:

<xs:attribute name="lang" type="xs:string"></xs:attribute>

Default and Fixed Values for Attributes:

Either a default value or a fixed value can be specified for an attribute. If no other value is specified, the default value is automatically assigned to the attribute.

Example:

<xs:attribute name="lang" type="xs:string" default="EN"></xs:attribute>

Explanation:

Here, the default value is “EN”.

When a fixed value is specified, we cannot specify another value. It is also automatically assigned to the attribute.

Example:

<xs:attribute name="lang" type="xs:string" fixed="EN"></xs:attribute>

Explanation:

Here, the fixed value is “EN”.

Optional and Required Attributes:

Being optional by default, we need to specify that the attribute is required, by using the “use” attribute.

Example:

<xs:attribute name="lang" type="xs:string" use="required"></xs:attribute>

Restrictions on Content:

A data type puts restrictions on the element’s or attribute’s content when it is defined for an XML element or attribute. For example, the element will not validate, if it is of type “xs:date” and contains a string like “Not Today”. To add our own restrictions, also known as facets, to the XML elements and attributes, we can take the help of the XML Schemas.