Specifying Attribute Constraints and Defaults

As with elements, you can specify the type of attributes, but unlike elements, attributes must be of a simple type. And 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, and the <xsd:attribute> element itself has a type attribute that gives the attribute's (simple) type. So how do you indicate whether an attribute is required or optional, or whether there's a default value, or even whether 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 and, if optional, 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:sequence>         <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:NMTOKEN"/>     <xsd:sequence>     <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 it is assigned in the document.

  • prohibited The attribute must not appear.

For example, this attribute declaration creates an integer attribute named counter whose value is always 400 :

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

And this attribute declaration 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:

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


Real World XML
Real World XML (2nd Edition)
ISBN: 0735712867
EAN: 2147483647
Year: 2005
Pages: 440
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net