Skip to main content

XSD Attributes

An attribute is declared as a simple type.

What is an Attribute?

Remember that a simple element can't have attributes.

So, if an element has attributes, it is a complex type.

But the attribute is defined as a simple type.

How to Define an Attribute?

The syntax for defining an attribute is as follows:

<xs:attribute name="my-name" type="my-type"/>

where

  • my-name is the name of the attribute
  • my-type is the data type of the attribute.

XML Schema has a lot of built-in data types. The most common type are:

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

Example

Attribute definition
<xs:attribute name="lang" type="xs:string"/>
Example
<lastname lang="EN">Nolan</lastname>

Default and Fixed Values for Simple Elements

Attributes can have a default value or a fixed value specified.

A default value is automatically assigned to the attribute when no other value is specified. For example default="EN".

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

A fixed value is also automatically assigned to the attribute, and you can't specify another value. For example fixed="EN".

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

Optional and Required Attributes

All attributes are optional by default.

To specify that an attribute is required, just 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, it places restrictions on the content of the element or attribute.

For example, if an XML element is of type xs:date and contains a string like Hello World, the element will not be validated.

note

With XML Schemas, you can also add your own restrictions to your XML elements and attributes. These restrictions are called facets. You can read more about facets here.