Imagine a technology that offered you all the power of a DTD without the associated unpleasantness of those strange symbols and arcane commands. Sounds too good to be true? Say hello to XML Schema.
So that takes care of elements - but what about attributes?
Attribute definitions typically follow element definitions, and are declared with the <xsd:attribute> element.
<xsd:attribute name="genre" type="xsd:string" />
An optional "use" attribute can be used to specify whether or not the attribute
is optional.
<!-- this attribute is optional -->
<xsd:attribute name="genre" type="xsd:string"
use="optional" />
<!-- this attribute is required-->
<xsd:attribute name="id"
type="xsd:integer" use="required" />
<!-- this attribute is not allowed -->
<xsd:attribute
name="address" type="xsd:string" use="prohibited" />
In order to see this in action, let's suppose I altered my document instance
to include an attribute:
This apparently minor change has quite a significant impact on the schema definition,
because the "person" element, previously defined as a simple type, must now be defined as a complex type. Since the "person" element does not have any nested child elements, we can pass up the <xsd:sequence> instruction within the element definition in favour of the <xsd:simpleContent> element and include an attribute definition within this element.
Here's the revised schema definition:
<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element
name="movie">
<xsd:complexType>
<xsd:sequence>
<!-- simple element
definition - title -->
<xsd:element name="title" type="xsd:string"/>
<!--
complex element definition - cast -->
<xsd:element name="cast">
<xsd:complexType>
<xsd:sequence>
<!--
since person has an attribute, it must be defined as a complex
element -->
<xsd:element
name="person" maxOccurs="unbounded">
<xsd:complexType>
<xsd:simpleContent>
<xsd:restriction
base="xsd:string">
<!-- attribute definition - sex -->
<xsd:attribute
name="sex" type="xsd:string" />
</xsd:restriction>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<!--
simple element definition - release date -->
<xsd:element name="release_date"
type="xsd:date" maxOccurs="1"
minOccurs="0"/>
<!-- simple element definition
- rating -->
<xsd:element name="rating" type="xsd:integer"/>
</xsd:sequence>
<!--
attribute definition for movie genre -->
<xsd:attribute name="genre" type="xsd:string"
/>
</xsd:complexType>
</xsd:element>
</xsd:schema>