XSD Attributes

All properties are declared as simple types.

What is an attribute?

Simple elements cannot have attributes. If an element has attributes, it is treated as a composite type. However, the attributes themselves are always declared as simple types.

How to declare an attribute?

The syntax for defining an attribute 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 and fixed values of properties

Properties can have specified default 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 properties

By default, properties are optional. To specify that a property is required, use the "use" attribute:

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

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 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 constraints to your XML elements and attributes. These constraints are called facets (editor's note: meaning the face of a polyhedron, which can be translated as constraint face). You will learn more about facets in the next section.