Creating Attributes

As with elements, with XML schemas you can specify the types of attributes. In XML documents, attribute values have to be quoted strings, and if you have, say, a number such as "100", the XML schema is able to indicate that such a number should be interpreted as an integer. To declare an attribute, you use the <xsd:attribute> element as in the following example, which declares an attribute named phone for the recordType type, which means that all elements of this type, such as <bank> in the XML document, will support this attribute:

<xsd:complexType name="recordType">
    <xsd:sequence>
        <xsd:element name="name" type="xsd:string"/>
        <xsd:element name="location" type="xsd:string"/>
        <xsd:element name="city" type="xsd:string"/>
        <xsd:element name="state" type="xsd:string"/>
    </xsd:sequence>
    <xsd:attribute name="phone" type="xsd:string"/>
</xsd:complexType>

Like <xsd:element>, <xsd:attribute> has a type attribute, and its attributes must always be of a simple type. You can also indicate whether an attribute is required or optional, or whether it has a default value. To do that, you use the <xsd:attribute> element's use and value attributes.

The use attribute specifies whether the attribute is required or optional—and if it is optional, whether the attribute's value is fixed or whether there is a default. For example, you can make the phone attribute optional like this:

<xsd:complexType name="recordType">
    <xsd:sequence>
        <xsd:element name="name" type="xsd:string"/>
        <xsd:element name="location" type="xsd:string"/>
        <xsd:element name="city" type="xsd:string"/>
        <xsd:element name="state" type="xsd:string"/>
    </xsd:sequence>
    <xsd:attribute name="phone" type="xsd:string"

           use="optional"/>
</xsd:complexType>

Here are the values you can give to the use attribute:

  • default — If you don't use the use attribute, its value is the default value set with the value attribute. If you do use it, its value is the value you assign it.
  • fixed — This value makes the attribute fixed. You can set its value by using the value attribute.
  • optional — This value makes the attribute optional, which means the attribute may have any value.
  • prohibited — This value means the attribute cannot be used.
  • required — This value makes the attribute required. The attribute can have any value.

The value attribute contains a value if you need to specify one. For example, the following attribute declaration creates an attribute named year with the integer fixed value "2005":

<xsd:attribute name="year" type="xsd:int" use="fixed" value="2005">

Here's another example of an attribute declaration. This example gives the integer attribute year the default value "2005":

<xsd:attribute name="year" type="xsd:int" use="default" value="2005">

+ Share This