In a previous article, we discussed about XSchema, its implications and also its elements. In this article, we would be discussing its attributes and the restrictions that are faced while scripting with XSchema.
First, let’s take a look at XSchema attributes. Simple elements cannot have attributes. If an element has attributes, it is considered to be of a complex type. But the attribute itself is always declared as a simple type.
1 |
<xs:attribute name="xxx" type="yyy"/> |
Where xxx is the name of the attribute and yyy specifies the data type of the attribute.
Attributes may have a default value OR a fixed value specified. A default value is automatically assigned to the attribute when no other value is specified. In the following example the default value is “EN”:
1 |
<xs:attribute name="lang" type="xs:string" default="EN"/> |
A fixed value is also automatically assigned to the attribute, and you cannot specify another value. In the following example the fixed value is “EN”:
1 |
<xs:attribute name="lang" type="xs:string" fixed="EN"/> |
Attributes are optional by default. To specify that the attribute is required, use the “use” attribute:
1 |
<xs:attribute name="lang" type="xs:string" use="required"/> |
Now, let’s take a look at XSchema restrictions. When an XML element or attribute has a data type defined, it puts restrictions on the element’s or attribute’s content. If an XML element is of type “xs:date” and contains a string like “Hello World”, the element will not validate. The following example defines an element called “age” with a restriction. The value of age cannot be lower than 0 or greater than 120:
1 2 3 4 5 6 7 8 |
<xs:element name="age"> <xs:simpleType> <xs:restriction base="xs:integer"> <xs:minInclusive value="0"/> <xs:maxInclusive value="120"/> </xs:restriction> </xs:simpleType> </xs:element> |
To limit the content of an XML element to a set of acceptable values, we would use the enumeration constraint. The example below defines an element called “car” with a restriction. The only acceptable values are: Audi, Golf, BMW:
1 2 3 4 5 6 7 8 9 |
<xs:element name="car"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="Audi"/> <xs:enumeration value="Golf"/> <xs:enumeration value="BMW"/> </xs:restriction> </xs:simpleType> </xs:element> |
To limit the content of an XML element to define a series of numbers or letters that can be used, we would use the pattern constraint. The example below defines an element called “letter” with a restriction. The only acceptable value is ONE of the LOWERCASE letters from a to z:
1 2 3 4 5 6 7 |
<xs:element name="letter"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="[a-z]"/> </xs:restriction> </xs:simpleType> </xs:element> |
There are several other important XSchem restriction which we would discuss in a future article reserved for XSchema restrictions.