Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

XML Schema Attributes

XSD Attributes


All attributes are declared as simple types.


What is an attribute?

Simple elements cannot have attributes. If an element has attributes, it is treated as a complex type. But 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:

Example

This is an XML element with an attribute:

Smith

This is the corresponding attribute definition:


Default and fixed values of attributes

An attribute can have a specified default or fixed value.

When no other value is specified, the default value is automatically assigned to the element.

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:


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 its content is a string like "Hello World", the element will not pass validation.

With XML schema, you can also add your own restrictions to your XML elements and attributes. These restrictions are called facets (Editor's note: meaning a face of a polyhedron, which can be translated as a limiting facet). You will learn more about facets in the next section.