Home > Articles > Programming > Java

Like this article? We recommend

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 tags—it 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 Passport–style 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020