XML Simple Attributes
Recall that attributes are used to provide additional information about an
XML element. Only complex elements are allowed to contain attributes, however,
the attributes themselves are considered simple types.
The syntax for declaring attributes in a Schema is shown below:
Attributes
<xsd:attribute name="attribute name" type="attribute data type"/>
Listing 3-9. Attribute syntax.
The attribute declaration is identical to the simple element. The attribute name is
specified, followed by the attribute type.
In the following XML file, the Tree element is defined and includes an attribute
tid
:
Trees.xml
<Tree tid="1">Red Oak</Tree>
Listing 3-10. Attribute declaration.
The Schema file shows how to define the tid
attribute:
Trees.xsd
<xsd:attribute name="tid" type="xs:integer"/>
Listing 3-11. Defining attributes.
When an XML element or attribute has a data type defined, it puts restrictions
on the element's or attribute's content. An attribute defined in the Schema
as type "integer" cannot be assigned the value "This is a String" in the XML
file.
Like simple elements, attributes may have a default value using the
default
attribute or a fixed value using the
fixed
attribute. A default value is automatically assigned
to the attribute when no other value is specified. A fixed value is also
automatically assigned to the attribute, and you cannot specify another value.
The tid
attribute is given a default value:
<xsd:attribute name="tid" type="xsd:integer" default="1111"/>
Listing 3-12. Assigning default values to attributes.
By default, attributes are optional. To specify that the attribute is required,
include the use attribute:
<xsd:attribute name="tid" type="xsd:integer" default="1111" use="required"/>
Listing 3-13. Specifying required attributes.
The tid
attribute is declared as a required attribute. If it is
not coded in the XML document, the file will not be considered valid.