Home > Articles > Programming

XML Schema

XML Schema is an initiative from the W3C that attempts to eliminate the problems with DTDs by replacing them with something better. XML Schemas are more flexible than DTDs, more powerful, and more familiar, as they use XML syntax.


Note - As of this writing, the XML Schema has advanced to "Candidate Recommendation" status at W3C, but Xerces version 1.2.3 uses the April 7, 2000 draft, located at

http://www.w3.org/TR/2000/WD-xmlschema-1-20000407/

http://www.w3.org/TR/2000/WD-xmlschema-2-20000407/

and

http://www.w3.org/TR/2000/WD-xmlschema-3-20000407/


To begin converting our DTD to a schema, we'll create a third text file called products.xsd (for XML Schema Document) and save it in the same directory as products.xml. The file should contain the text in Listing 3.17.

Listing 3.17  products.xsd: The Basic Schema Document

0: <?xml version="1.0" ?>
1: <schema>
2:
3: </schema>

Notice that this is just an XML document, same as all the others we've used so far. All definitions we create will be part of the schema element. This file is called our schema document. The file we're validating—our XML file—is called our instance document, because it's an instance of the data that we're defining.

Now, you may remember that an XSL style sheet was also an XML document, and that we separated the XSL commands from the output using namespaces—specifically, the xsl: namespace. We're going to do the same with our schema document, but namespaces allow us to do something else: We can exclude elements from validation, if we want to.

To do this, we'll create a namespace that points to schema validation, and then tell the parser that any elements that are not part of that namespace need to be processed according to our schema document. We'll do this by making the changes in Listing 3.18 to products.xml.

Listing 3.18  products.xml: Associating Our XML with a Schema Document

<?xml version="1.0"?>
<products xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation='products.xsd'>

<vendor webvendor="full" id="conners">
...

Now we're ready to start converting our DTD to a Schema.

Datatypes

The concept behind XML Schema is that we start with simple datatypes (such as a string of text or a number) and build them into more complex structures, known as complex datatypes. This in and of itself is an improvement over DTDs, where we couldn't specify that, say, a price had to be a number. Some of the simple types built into XML Schema include the following:

  • string—This is simple text.

  • numeric types—These include float, double, decimal, integer, nonPositiveInteger, negativeInteger, long, int, short, byte, nonNegativeInteger, unsignedLong, unsignedInt, unsignedShort, unsignedByte, and positiveInteger.

  • time-related types—These include timeInstant, timeperiod, month, year, century, recurringDate, recurringDay, timeDuration, recurringDuration, date, and time.

  • XML 1.0 tokenized types—These are type names that have special meanings, such as ID, IDREF, ENTITY, and NMTOKEN.

Let's start by creating the elements that use simple datatypes in Listing 3.19.

Listing 3.19  Our Simple Elements

0: <?xml version="1.0">
1: <schema>
2: 
3: <element name="vendor_name" type="string"/>
4: <element name="b" type="string"/>
5: <element name="i" type="string"/>
6: <element name="p" type="string"/>
7: <element name="short_desc" type="string"/>
8: <element name="product_desc" type="string"/>
9: <element name="giveaway_item" type="string"/>
10:<element name="giveaway_desc" type="string"/>
11:<element name="long_desc" type="string"/>
12:<element name="product_id" type="string"/>
13:
14:</schema>

Now, it just so happens that all the simple types we had originally defined as #PCDATA really were strings, but if we had any that needed to be, say, numbers or dates, we would define them here.

Next, we'll start to build up the elements that use these simple elements into complex datatypes. The simplest way of doing this is shown in Listing 3.20.

Listing 3.20  products.xsd: Creating an Element of Elements

0: <?xml version="1.0"?>
1: <schema>
2:
3: <element name="vendor_name" type="string"/>
4: <element name="b" type="string"/>
5: <element name="i" type="string"/>
6: <element name="p" type="string"/>
7: <element name="short_desc" type="string"/>
8: <element name="product_desc" type="string"/>
9: <element name="giveaway_item" type="string"/>
10:<element name="giveaway_desc" type="string"/>
11:<element name="long_desc" type="string"/>
12:<element name="product_id" type="string"/>
13:
14:<element name="giveaway">
15:   <element name="giveaway_item" type="string"/>
16:   <element name="giveaway_desc" type="string"/>
17:</element>
18:
19:</schema>

On lines 14 through 17, we're building the definition of the giveaway element the same way that we'll build the element itself: by nesting the elements inside it. A giveaway consists of a giveaway_item and a giveaway_desc, so we include them as part of this definition on lines 15 and 16. We also add attributes to an element this way, as shown in Listing 3.21.

Listing 3.21  products.xsd: Creating Attributes

... 
16:   <element name="giveaway_desc" type="string"/>
17:</element>
18:
19:<element name="special" type="string">
20:  <attribute name="specialtype" type="string" use="fixed" value="weekly" />
21:</element>
22:
23:</schema>

Here, on lines 19 through 21 we're adding attributes much the same way we added them under XSL. We do, however, have two new values to look at on line 20. The use value (in this case "fixed") tells the processor whether this attribute is implied, required, and so on. If there is a default to be specified, it will be found as the value, as we did here with "weekly".

Next we'll construct some of the more complex elements. So far we've looked at elements that will contain text. In Listing 3.22, we will look at elements that are made up of other elements.

Listing 3.22  Specifying Element Occurrences

... 
19:<element name="special" type="string">
20: <attribute name="specialtype" type="string" use="fixed" value="weekly" />
21:</element>
22:
23:<element name="item" content="elementOnly">
24:   <element ref="product_desc" />
25:   <element ref="price" minOccurs="0" maxOccurs="unbounded"/>
26:</element>
27:
28:<element name="suite" content="elementOnly">
29:   <element ref="product_id" />
30:   <element ref="short_desc" />
31:   <element ref="long_desc" />
32:   <element ref="price" />
33:   <element ref="product" minOccurs="0" maxOccurs="unbounded" />
34:</element>
35:
36:<element name="product" content="elementOnly">
37:   <element ref="product_id" />
38:   <element ref="short_desc" />
39:   <element ref="product_desc" minOccurs="0" maxOccurs="1" />
40:   <element ref="price" minOccurs="1" maxOccurs="unbounded" />
41:   <element ref="item" minOccurs="0" maxOccurs="unbounded" />
42:   <element ref="inventory" minOccurs="0" maxOccurs="unbounded" />
43:   <element ref="giveaway" minOccurs="0" maxOccurs="1" />
44:</element>
45:
46:<element name="vendor" content="elementOnly">
47:   <element ref="vendor_name" />
48:   <element ref="advertisement" minOccurs="0" maxOccurs="1" />
49:   <element ref="suite" minOccurs="0" maxOccurs="unbounded" />
50:   <element ref="product" minOccurs="0" maxOccurs="unbounded" />
51:   <attribute name="webvendor" type="string" use="required" />
52:   <attribute name="id" type="ID" use="required" />
53:</element>
54:
55:</schema>

There's a lot of new material here, but most of it is along the same lines, so let's start with items on lines 23 through 26. First of all, an item element can contain only other elements, which is what content="elementOnly" means on line 23. The actual elements themselves are specified on lines 24 and 25, but because both product_desc and price appear elsewhere, rather than defining them here, we'll simply refer to the datatypes we've already created.

On line 25, we see the first of the attributes that limit how many times an element can occur. When we created the DTD, we specified a price element within an item element with *, meaning that it could occur 0 or more times. Now we're duplicating this requirement with minOccurs and maxOccurs. The advantage here over a DTD is that if we wanted to, we could set these values to specific integers, as opposed to just 0, 1, or unbounded.

We've used the same information to describe the suite element on lines 28 through 34, product on lines 36 through 44, and vendor on lines 46 through 53.

That leaves us with price, inventory, advertisement, and our root element, products. We'll look at advertisement and products in a moment, but price and inventory have a special complication to them: enumerated values. In Listing 3.23, we see how to specify enumerated values for an attribute.

Listing 3.23  products.xsd: Enumerated Values

... 
52:   <attribute name="id" type="ID" use="required" />
53:</element>
54:
55:<element name="price" type="decimal">
56: <attribute name="pricetype" type="NMTOKEN" use="default" value="retail">
57:    <simpleType base="string">
58:      <enumeration value="cost"/>
59:      <enumeration value="sale"/>
60:      <enumeration value="retail"/>
61:      <enumeration value="starting"/>
62:    </simpleType>
63: </attribute>
64: <attribute name="color" type="string" use="implied" />
65:</element>
66:
67:<element name="inventory" type="integer">
68: <attribute name="location" type="NMTOKEN" use="default" value="warehouse">
69:    <simpleType base="string">
70:      <enumeration value="warehouse"/>
71:      <enumeration value="showroom"/>
72:    </simpleType>
73: </attribute>
74:  <attribute name="color" type="string" use="implied" />
75:</element>
76:
77:</schema>

On lines 55 through 65, we're specifying the price element. The first thing to notice is that on line 55 we specified the type as decimal, which we certainly couldn't have done with a DTD. On lines 56 through 63, we're defining the pricetype attribute. This attribute is a new datatype, NMTOKEN. That means that we can use only certain defined values, or tokens. On lines 57 through 62, we're defining those values. The simpleType element tells the processor that ultimately, we're going to wind up with a string. The elements on lines 58 through 61 place further conditions on the value. In this case, we're specifying certain values, but other restrictions are possible.

Line 64 is just a straight attribute definition, as we've already seen, and we're repeating the process for the inventory element on lines 67 through 75.

We'll create the products element in Listing 3.24.

Listing 3.24  products.xsd: Creating the Root Element

... 
74:  <attribute name="color" type="string" use="implied" />
75:</element>
76:
77:<element name="products" content="elementOnly">
78:   <choice maxOccurs="unbounded">
79:    <element ref="vendor" />
80:    <element ref="special" />
81:   </choice>
82:</element>
83:
84:</schema>

Our DTD specified that the products element could have any number of vendors or specials, in no particular order. To achieve this same result in the schema, we can use the choice element. Alone, it allows one of those elements to be present. After we add maxOccurs="unbounded", any number of them is allowed.

Finally, we're down to our problem child, advertisement. It's our problem child because it has both text and elements. This is known as mixed content. We'll take care of it in Listing 3.25.

Listing 3.25  Specifying Mixed Content

... 
82:</element>
83:
84:<element name="advertisement" content="mixed">
85:   <element name="ad_sentence" content="mixed">
86:     <element ref="b" minOccurs="0"/>
87:     <element ref="i" minOccurs="0"/>/>
88:     <element ref="p" minOccurs="0"/>/>
89:   </element>
90:</element>
91:
92:</schema>

I've included this example here even though it's not really what we want. When we defined mixed content with the DTD, we were not able to control the order of content, or even whether items appeared. With schemas, we can, by specifying the content as it is in Listing 3.25. In this case, however, we don't care about the order, so it's better to use a choose element as we did in Listing 3.24.

Features Still to Come

Two of the most promising features of XML Schema, uniqueness and referential integrity, have not been implemented in the version of Xerces that we are using. It is, however, worth taking a few moments to discuss how they work.

Uniqueness, as the name implies, is the ability to specify that every value of a particular element or attribute must be different; there can be no duplicates. Referential integrity, as we discussed earlier, is when we specify that one value, such as a special's vendor_id attribute, must match a value elsewhere, such as the vendor's id attribute.

For both uniqueness and referential integrity, we need to create keys. These keys involve the element that the key is attached to and the field or attribute that is being checked. For instance, to specify that we want the id to be unique for a vendor, we would add the following to the schema:

<unique>
   <selector>/products/vendor</selector>
   <field>vendor[@id]</field>
</unique>

If that selector looks familiar, it should. It's an XPath expression, just like the ones that we used with XSL. This way, we can distinguish between a product_id, and a vendor id.

To create referential integrity, we first create the vendor_id as a key:

<key name="vendor_key">
<selector>/products/vendor</selector>
<field>vendor[@id]</field>
</key>

We then create a keyref type:

<keyref refer="vendor_key">
<selector>/products/special</selector>
<field>special[@vendor_id]</field>_</keyref>

This forces any vendor_id attribute to match the vendor_key.

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