In addition to declaring what elements can be used in an XML document, we also need to declare any attributes used. Attribute declarations indicate the element that an attribute is assigned to, what type of data the attribute contains, and whether it is required or optional. With XML Schema, we also have the ability to declare a default value for an attribute if desired. Declaring an attribute in XML Schema is very similar to declaring a simple element, as seen in the following example:
<xs:attribute name="species" type="xs:string" />
Exiting code block.
With this example, we can see that the attribute is named species, and the data it will contain is likely a string of text. Once we’ve declared an attribute, in order to use it in an XML document, we need to associate it with an element. As a reminder, attributes can only be used with complex elements - if you have a simple element that needs an attribute, you’ll need to change it to a complex element before associating the attribute with the element.
The following example demonstrates how to associate an attribute with an element:
<xs:element name="animal"> <xs:complexType> <xs:attribute ref="species" use="required" /> </xs:complexType> </xs:element>
Exiting code block.
This example declares an element named animal, which has an attribute named species. Additionally,
use="required" indicates that this attribute must be used when using the element in an XML document, or the document won’t validate. (We’ll explore how to validate an XML document with an XML Schema document later on.)
Now that we know the syntax for declaring attributes, let’s declare the attributes we want to use in the document - posting-date, which will include the date the job postings were updated, and id, which contains the ID number for a specific job. Once we've declared the attributes, we'll then associate them with the elements they'll be used with. We'll also ensure that the posting date and each job's ID are included in the document by making those attributes required.