Specifying Attribute Constraints and Defaults

As with elements, you can specify the type of attributes. Unlike with elements, however, attributes must be of a simple type. In addition, you don't use minOccurs and maxOccurs for attributes because attributes can appear only once, at most. Instead, you use a different syntax when constraining attributes.

You declare attributes with the <xsd:attribute> element. The <xsd:attribute> element itself has a type attribute that gives the attribute's (simple) type. So how do you indicate if an attribute is required or optional, or if there's a default value, or even if the value of the attribute is fixed at a certain value? You use the <xsd:attribute> element's use and value attributes.

The use attribute specifies whether the attribute is required or optional; if the attribute is optional, the use attribute specifies whether the attribute's value is fixed or whether there is a default. The second attribute, value, holds any value that is needed.

For example, I've added an attribute named phone to the Address type; this attribute is of type xsd:string, and its use is optional:

<xsd:complexType name="address">
    <xsd:element name="name" type="xsd:string"/>
    <xsd:element name="street" type="xsd:string"/>
    <xsd:element name="city" type="xsd:string"/>
    <xsd:element name="state" type="xsd:string"/>
    <xsd:attribute name="phone" type="xsd:string"
        use="optional"/>
</xsd:complexType>

Here are the possible values for the use attribute:

  • required. The attribute is required and may have any value.

  • optional. The attribute is optional and may have any value.

  • fixed. The attribute value is fixed, and you set its value with the value attribute.

  • default. If the attribute does not appear, its value is the default value set with the value attribute. If it does appear, its value is the value that it is assigned in the document.

  • prohibited. The attribute must not appear.

For example, consider this attribute declaration:

<xsd:attribute name="counter" type="xsd:int
"use="fixed" value="400">

This declaration creates an integer attribute named counter, whose value is always 400. Now consider this attribute declaration:

<xsd:attribute name="counter" type="xsd:int
"use="default" value="400">

This means that the counter attribute has a default value of 400 if it is not used, and it has the value assigned to it if it is used.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset