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:
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"> |