- Introduction
- Writing a Custom Schema
- Implementing XML Schema Types
- From Here...
Implementing XML Schema Types
The real beauty of XML Schema is that once a document has been validated against a schema it becomes more than just a set of elements and tagsit becomes a set of types and instances. The elements contained within a document are processed and the type and instance information from the document is exposed to the consuming software agent. After validation, the information is contained in an XML Document that's called a post schema-validation Infoset (usually referred to as just Infoset). Infosets make it possible to reflect over the logical contents of a document, just as in some object-oriented programming languages, revealing the power of XML Schema as a platform-independent type system. To demonstrate, let's start to build some types and see how the (logical) type system works with the (physical) document.
Creating Simple Types via Restriction
As mentioned earlier, XML Schema provides 44 simple types with which to build content models. However, unlike simple types in most programming languages, these built-in XML Schema types can be used as base types for the creation of specialized subtypes. There is one key difference to note when defining a subtype of a simple type in XML Schema: You don't change the structure of the type (as happens when inheriting from a base class in Java), but instead change the subset of values that the subtype can handle. For example, you might specify a subtype of the simple type string that can only hold a value representing a postal code. Similarly, you might restrict the date type to valid dates within a particular century.
You create a subtype of a simple type in XML Schema using the restriction element. Within this element, you specify the name of the simple type whose set of permissible values you want to restrict (known as the base type), and indicate how the restriction will be applied. Restrictions are then specified by constraining facets of the base simple type. Each facet allows you to constrain simple types in a different way. For example, to create a simple type to validate a British postal code, you could constrain a string type using the pattern facet with a (complicated!) regular expression as shown in Listing 3.
Listing 3 The pattern Facet
<simpleType name="PostcodeType"> <restriction base="string"> <pattern value="(GIR 0AA)|((([A-Z][0-9][0-9]?) |(([A-Z][A-HJ-Y][0-9][0-9]?)|(([A-Z][0-9][A-Z])| [A-Z][A-HJ-Y][0-9]?[A-Z])))) [0-9][A-Z]{2})"/> </restriction> </simpleType>
The pattern specified in Listing 3 allows only values matching the British postal code standard, such as SW1A 1AA (which identifies the Prime Minister's residence in 10 Downing Street, among other London landmarks) or W1A 1AE (the American Embassy in London). Formally, these rules are defined by the British Post Office as follows:
The first part of the code before the space character (known as the outward code) can consist of two, three, or four alphanumeric characters followed by a space. The second part of the code (the inward code) is three characters long and is always one digit followed by two letter characters. Permitted combinations according to the PostcodeType type are as follows (where A is a letter character and N is a number):
AN NAA
ANN NAA
AAN NAA
AANN NAA
ANA NAA
AANA NAA
The letters I and Z are not used in the second alpha position (except in GIR 0AA, which is a historical anomaly in the British postal system).
The second half of the code never uses the letters C, I, K, M, O, or V.
Any divergence from this form will mean that the element is not a valid PostcodeType instance.
Similarly, you might want to create an enumeration in which only specific values are allowed within a type. Listing 4 shows an example in which the XML Schema string type is restricted to allow only certain values representing a number of world currencies.
Listing 4 The enumeration Facet
<xs:simpleType name="CurrencyType"> <xs:restriction base="xs:string"> <xs:enumeration value="GBP"/> <xs:enumeration value="AUD"/> <xs:enumeration value="USD"/> <xs:enumeration value="CAD"/> <xs:enumeration value="EUR"/> <xs:enumeration value="YEN"/> </xs:restriction> </xs:simpleType>
The CurrencyType declared in Listing 4 would validate elements such as <my-currency>GBP</my-currency>, but would not validate <your-currency>DM</your-currency> because the string DM is not part of this simpleType restriction (and Deutsch Marks are no longer legal tender, anyway).
Continuing in a monetary theme, suppose we create a StockPriceType type restricting the number of digits after the decimal point to a maximum of two. The restricted XML Schema decimal type in Listing 5 can be used to validate elements that have the form <msft>25.52</msft> or <sunw>3.7</sunw>.
Listing 5 The fractionDigits Facet
<xs:simpleType name="StockPriceType"> <xs:restriction base="xs:decimal"> <xs:fractionDigits value="2"/> </xs:restriction> </xs:simpleType>
To specify sizes of allowed values, use the length, maxLength, and minLength facets. For example, a sensible precaution to take when creating computer passwords is to mandate a minimum length for security, and a maximum length for ease of use (and thus indirectly for security). Listing 6 uses the maxLength and minLength facets to create such a PasswordType.
Listing 6 maxLength and minLength Facets
<xs:simpleType name="PasswordType"> <xs:restriction base="xs:string"> <xs:minLength value="6"/> <xs:maxLength value="10"/> </xs:restriction> </xs:simpleType>
When applied to an element in a document, the PasswordType in Listing 6 allows values such as <password>kather1ne</password> but not <password>carol</password>, based on the number of characters contained in the element. Of course, if a particularly overbearing system administration policy was put into place, you could end up having passwords of a long, fixed length using the length facet instead of minLength and maxLength.
Similarly, you can specify maximum and minimum values with the maxInclusive, minInclusive, minExclusive, and maxExclusive facets. Suppose you want to define the range of seconds in a minute, for timing purposes. Listing 7 shows a simpleType called SecondsType in which the int type from XML Schema is constrained to accept the values from 0 (inclusive) to 59 (60 exclusive).
Listing 7 minInclusive and maxExclusive Facets
<xs:simpleType name="SecondsType"> <xs:restriction base="xs:int"> <xs:minInclusive value="0"/> <xs:maxExclusive value="60"/> </xs:restriction> </xs:simpleType>
Working in the opposite direction, Listing 8 defines the years in the 20th century, where the years are captured as being positive integers (which have the range from 1 upwards) from 1901 (1900 exclusive) through to 2000 (inclusive).
Listing 8 minExclusive and maxInclusive Facets
<xs:simpleType name="TwentiethCenturyType"> <xs:restriction base="xs:positiveInteger"> <xs:minExclusive value="1900"/> <xs:maxInclusive value="2000"/> </xs:restriction> </xs:simpleType>
The totalDigits facet puts an upper limit on the number of digits that a number-based type can contain. For example, for around the next 8,000 years, a year number will contain a total of four digits. Thus, we can create a simple year type using the totalDigits facet to constrain the number of digits to four. In Listing 9, the positiveInteger type from XML Schema is restricted to those positive integers that have at most four digits.
Listing 9 The totalDigit Facet
<xs:simpleType name="YearType"> <xs:restriction base="xs:positiveInteger"> <xs:totalDigits value="4"/> </xs:restriction> </xs:simpleType>
The final facet for restricting the value space of simple types is whiteSpace. This facet allows a simple type implementer to specify how any whitespace (tabs, spaces, carriage returns, and so on) is handled when appearing inside elements. There are three options for the whiteSpace facet:
Option |
Description |
preserve |
The XML processor doesn't remove any whitespace characters. |
replace |
The XML processor replaces all whitespace with spaces. |
collapse |
Same as replace, but with all preceding and trailing whitespace removed. |
The whiteSpace facet is often applied along with other facets to deal with extraneous whitespace. For example, if we add a whiteSpace facet to the YearType from Listing 9, the XML processor that processes instances of this type can deal with any unimportant whitespace. In Listing 10, the whiteSpace facet is set to collapse, which effectively rids the value of any unwanted whitespace after it has been processed.
Listing 10 The whiteSpace Facet
<xs:simpleType name="YearType"> <xs:restriction base="xs:positiveInteger"> <xs:totalDigits value="4"/> <xs:whiteSpace value="collapse"/> </xs:restriction> </xs:simpleType>
If the XML processor receives an element of type YearType such as the following:
<moon-landing> 1969 </moon-landing>
the whiteSpace collapse facet reduces it to this:
<moon-landing>1969</moon-landing>
Simple Types: List and Union
Restriction is only one means of creating new simple types. XML Schema supports two additional mechanisms for creating new simple types: union and list.
The list mechanism is the simpler of the two to understand. In short, simple types created via the list mechanism are a whitespace-delimited list of values from the base type. For example, we can create a list of instances of YearType from Listing 9 to create the YearsType, as shown in Listing 11.
Listing 11 Creating New Simple Types with list
<xs:simpleType name="YearType"> <xs:restriction base="xs:positiveInteger"> <xs:whiteSpace value="collapse"/> <xs:totalDigits value="4"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="YearsType"> <xs:list itemType="YearType"/> </xs:simpleType>
The YearsType type defined in Listing 11 can then be used to validate instances of the YearsType such as the years element in Listing 12.
Listing 12 Instance of the YearsType Type
<WWII> 1939 1940 1941 1942 1943 1944 1945 1946</WWII>
The union mechanism is slightly more subtle than list. It allows the aggregation of the value spaces of two types to be combined into the value space of a new single simple type. Suppose we have two simple types that represent fruits and vegetables, as shown in Listing 13.
Listing 13 FruitType and VegetableType Simple Types
<xs:simpleType name="FruitType"> <xs:restriction base="xs:string"> <xs:enumeration value="ORANGE"/> <xs:enumeration value="APPLE"/> <xs:enumeration value="BANANA"/> <xs:enumeration value="KIWI"/> </xs:restriction> </xs:simpleType> <xs:simpleType name="VegetableType"> <xs:restriction base="xs:string"> <xs:enumeration value="POTATO"/> <xs:enumeration value="CABBAGE"/> <xs:enumeration value="TURNIP"/> <xs:enumeration value="LEEK"/> </xs:restriction> </xs:simpleType>
We can use the FruitType and VegetableType types in Listing 13 to create a FruitAndVegetableType via a union, as shown in Listing 14.
Listing 14 Creating a New Simple Type via a union
<xs:simpleType name="FruitAndVegetableType"> <xs:union memberTypes="FruitType VegetableType"/> </xs:simpleType>
The resulting FruitAndVegetableType type can be used to validate elements such as these:
<organically-grown>BANANA</organically-grown> <menu-item>POTATO</menu-item>
because both BANANA and POTATO are valid values for the FruitAndVegetableType type.
Complex Types
As well as creating specialized versions of the XML Schema simple types, you can also create new complex types by aggregating existing types into a structure. XML Schema supports three means of aggregating types with three different complex type compositors:
complexType Compositors
Compositor |
Description |
sequence |
Specifies that the contents of the complex type must appear as an ordered list. |
choice |
Allows a choice of any of the contents of the complex type. |
all |
Specifies that the contents of the complex type appear as an unordered list. |
While the semantics of the compositors vary, the syntax of all are similar. To use any of the compositors, simply declare a new complex type with a compositor as its child element, as shown in Listing 15.
Listing 15 Declaring a New complexType Using the sequence Compositor
<xs:complexType name="AddressType"> <xs:sequence> <xs:element name="number" type="xs:string"/> <xs:element name="street" type="xs:string"/> <xs:element name="city" type="xs:string"/> <xs:element name="state" type="xs:string"/> <xs:element name="post-code" type="xs:string"/> </xs:sequence> <xs:attribute name="business-address" type="xs:boolean"/> </xs:complexType>
Listing 15 creates a new complexType called AddressType by aggregating five elements of type string that represent a mailing address, and a single attribute of type boolean to indicate whether this address is business or residential. With the AddressType in Listing 15, we can validate elements such as the address element in Listing 16.
Listing 16 A Valid Instance of the AddressType Type
<address> <number>221b</number> <street>Baker Street</street> <city>London</city> <state>N/A</state> <post-code>NW1 6XE</post-code> </address>
The all compositor is similar to the sequence compositor except that ordering constraint is relaxed. Although the elements contained within an all compositor must be present, the order in which they appear is unimportant from the point of view of the XML processor.
In Listing 17, the PurchaseOrderType uses the all compositor to create an aggregate structure containing mandatory order-number and item elements, and an optional description element (specified by the minOccurs="0" attribute).
Listing 17 Using the all Compositor
<xs:complexType name="PurchaseOrderType"> <xs:all> <xs:element name="order-number" type="xs:positiveInteger"/> <xs:element name="item" type="xs:string"/> <xs:element name="description" type="xs:string" minOccurs="0"/> </xs:all> </xs:complexType>
The PurchaseOrderType type from Listing 17 can be used to validate the instances shown in Listing 18, in which only one instance includes the description element.
Listing 18 Valid PurchaseOrderType Instances
<purchase-order> <order-number>1002</order-number> <item>11025-32098</item> <description>Personal MP3 Player</description> </purchase-order> <purchase-order> <item>44045-23112</item> <order-number>5290</order-number> </purchase-order>
Using the choice compositor, we can force the contents of part of a document to be one of a number of possible options. For example, in Listing 19 the UserIdentifierType allows a user to supply either a login identifier or Microsoft Passportstyle single-sign on credentials to log into a system. (This type of arrangement is typical in e-commerce sites.)
NOTE
This hypothetical example has been shortened for clarity, and the types used are not representative of the actual Passport API.
Listing 19 Using the choice Compositor
<xs:complexType name="UserIdentifierType"> <xs:choice> <xs:element name="login-id" type="xs:string"/> <xs:element name="passport" type="xs:anyURI"/> </xs:choice> </xs:complexType>
The UserIdentifierType can be used to validate elements containing either a login-id or a passport element, but not both. Therefore, both elements shown in Listing 20 can be validated against the UserIdentifierType.
Listing 20 Valid UserIdentifierType Elements
<logon> <login-id>chewbacca@wookie.org</login-id> </logon> <logon> <passport> http://passport.example.org/uid/2235:112e:77fa:9699:aad1 </passport> </logon>
The minOccurs and maxOccurs attributes can be used within a choice compositor to expand the basic exclusive OR operation that choice provides. This technique supports selection based on quantity as well as content, as exemplified in Listing 21.
Listing 21 Choosing Elements Based on Cardinality
<xs:complexType name="DrinksMenuType"> <xs:choice> <xs:element name="beer" type="b:BeerType" minOccurs="0" maxOccurs="2"/> <xs:element name="wine" type="w:WineType" minOccurs="0" maxOccurs="1"/> </xs:choice> </xs:complexType>
Using the DrinksMenuType type, we can specify using the minOccurs and maxOccurs attributes that our choice can be either two beers or one drink of wine, as shown in Listing 22.
Listing 22 Instance Documents Constrained by choice
<!-- Either two beers... --> <drinks> <b:beer type="bitter"/> <b:beer type="lager"/> </drinks> <!-- ... Or a single drink of wine --> <drinks> <w:wine country="France" grape="Pinot Noir" year="1998"/> </drinks>
We could also select based on quantity of a single item. For example, envision a choice in which beer can be sold in four, six, and twelve packs by simply setting the minOccurs and maxOccurs attributes to 4, 6, and 12, respectively, as shown in Listing 23.
Listing 23 Choice Based on Cardinality
<xs:complexType name="DrinksMenuType"> <xs:choice> <xs:element name="beer" type="xs:string" minOccurs="4" maxOccurs="4"/> <xs:element name="beer" type="xs:string" minOccurs="6" maxOccurs="6"/> <xs:element name="beer" type="xs:string" minOccurs="12" maxOccurs="12"/> </xs:choice> </xs:complexType>
This concludes our discussion of compositors. I've shown how to aggregate existing types into new types in a variety of ways (sequence, choice, all) and some of the variations on those themes (such as choice by cardinality).
As another option, you can create new types not only by aggregating existing types, but by aggregating existing types and textual content. For example, you might want to mix textual information and structured data to create a letter, as shown in Listing 24.
Listing 24 Mixed Textual and Element Content
<letter> Dear Professor <name>Einstein</name>, Your shipment (order: <orderid>1032</orderid> ) will be shipped on <shipdate>2004-06-14</shipdate>. </letter>
NOTE
This example is adapted from the W3Schools example.
You need to create a type to mix elements and text (by default, types don't allow such mixtures), with a schema such as that shown in Listing 25.
Listing 25 Schema Supporting Mixed Textual and Element Content
<xs:element name="letter"> <xs:complexType mixed="true"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="orderid" type="xs:positiveInteger"/> <xs:element name="shipdate" type="xs:date"/> </xs:sequence> </xs:complexType> </xs:element>
To support mixed textual and element content, create a complexType with mixed content. Thus, when the mixed attribute is set to true (the default is false), the resulting type can mix elements and text as shown in the letter example in Listing 24.