Home > Articles > Web Services > XML

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Differences Between DTDs and Schema

The critical difference between DTDs and XML Schema is that XML Schema utilize an XML-based syntax, whereas DTDs have a unique syntax held over from SGML DTDs. Although DTDs are often criticized because of this need to learn a new syntax, the syntax itself is quite terse. The opposite is true for XML Schema, which are verbose, but also make use of tags and XML so that authors of XML should find the syntax of XML Schema less intimidating.

The goal of DTDs was to retain a level of compatibility with SGML for applications that might want to convert SGML DTDs into XML DTDs. However, in keeping with one of the goals of XML, "terseness in XML markup is of minimal importance," there is no real concern with keeping the syntax brief.

TIP

The documentation provided by the W3C related to the Working Groups and Recommendations can be extremely useful in understanding the design philosophy and goals of a technology. If you are considering development work with a new technology, you should consult the W3C documentation to learn about the appropriate uses for the technology and to keep up with changes in a working draft or updates to a published Recommendation.

However, you might care if you are dealing with a complex Schema. Schema can become long rather quickly. In general, DTDs tend to be shorter, since the syntax is more compact—not necessarily any less convoluted, but usually shorter.

So what are some of the other differences which might be especially important when we are converting a DTD? Let's take a look.

Typing

The most significant difference between DTDs and XML Schema is the capability to create and use datatypes in Schema in conjunction with element and attribute declarations. In fact, it's such an important difference that one half of the XML Schema Recommendation is devoted to datatyping and XML Schema. We cover datatypes in detail in Part III of this book, "XML Schema Datatypes."

It's very easy to see how datatypes can be useful in Schema design. Take, for example, a ZIP code element. Using a DTD, we would only be able to specify that a <zip> element was text. That would mean that someone could enter W321GWG@(!#@ as a ZIP code, and it would still be considered valid. However, if we are following the U.S. ZIP Code format, this is obviously not valid. Using XML Schema, we could actually create a datatype for ZIP codes using regular expressions (simply a pattern that matches a specific set of strings) that would limit the zip element to the standard 5-digit ZIP code. We could also create a datatype to deal with ZIP+4 if we wanted. For example:

<xs:simpleType name="zip">
 <xs:restriction base="xs:string">
 <xs:pattern value="[0-9]{5}(\-)?([0-9]{4})?"/>
 </xs:restriction>
</xs:simpleType>

makes use of a regular expression (in the pattern value) to see if the string matches the ZIP+4 format. We'll talk more about both datatypes and regular expressions in Chapter 12, "Representing and Modeling Data."

The ability to get that specific with the datatypes of the content for our elements and attributes is a very powerful aspect of XML Schema.

Occurrence Constraints

Another area where DTDs and Schema differ significantly is with occurrence constraints. If you recall from our previous examples in Chapter 2, "Schema Structure" (or your own work with DTDs), there are three symbols that you can use to limit the number of occurrences of an element: *, + and ?.

The * allows you to specify that an element may occur any number of times, the + signifies that an element may occur one or more times, and ? limits the element occurrence to zero or one. So, let's say we have an element called carton, which can contain egg elements. Table 3.1 shows how we might use the DTD occurrence operators to limit the number of times the elements may appear in an XML document.

Table 3.1 Limiting Element Occurrences in a DTD

DTD Syntax

Meaning

<!ELEMENT carton (egg*)>

carton could contain any number of eggs.

<!ELEMENT carton (egg+)>

carton must contain at least one egg, but there is no limit to the maximum number of eggs.

<!ELEMENT carton (egg?)>

carton does not have to contain any eggs, but may contain one.

<!ELEMENT carton (egg)>

carton may contain one, and only one egg.


As you can see, these options are a little limited. For example, how often do you buy a carton of one egg? And are you aware of any cartons that can hold an infinite number of eggs? What if you wanted to define a carton that could hold exactly a half-dozen eggs? You could do that; the declaration would look like this:

<!ELEMENT carton (egg, egg, egg, egg, egg, egg)>

What if you wanted to be more flexible, and say that carton had a minimum of a half-dozen eggs, but it could store up to a dozen? That could be done in a DTD too, but it's ugly looking:

<!ELEMENT carton (egg, egg, egg, egg, egg, egg, egg?, egg?, egg?, egg?, egg?, egg?)>

That declaration specifies that there are six egg elements which occur once and only once, and then six more egg elements which may occur once, but don't have to. The result is that we must have 6 egg elements in our carton but we can have up to 12.

As you can see, the definitions for accomplishing this level of granularity are really ugly. Schema allow a much cleaner mechanism for occurrence restraints, the minOccurs and maxOccurs attributes, which allow you to specify the minimum and maximum number of occurrences of an element:

<xs:element name="carton">
 <xs:complexType>
  <xs:sequence>
   <xs:element name="egg" type="xs:string"
      minOccurs="6" maxOccurs="12" />
  </xs:sequence>
 </xs:complexType>
</xs:element>

This is a much cleaner mechanism for defining elements which have specific occurrence constraints. If you need this type of control over the elements in your schema, DTDs fall short. This is the up side of verbosity in XML Schema: The added descriptiveness allows Schema to be more human-readable.

Enumerations

An enumeration is simply a list of values. Surfing the Web, you encounter enumerations every time you come across a pull-down menu: The menu presents you with a predefined list of choices. Those choices, or enumerations, can be defined in a DTD for a list of attributes.

So, let's say we had a <shirt> element, and we wanted to be able to define a size attribute for the shirt, which allowed users to choose a size: small, medium, or large. Our DTD would look like this:

<!ELEMENT item (shirt)>
<!ELEMENT shirt (#PCDATA)>
<!ATTLIST shirt
    size_value (small | medium | large)>

That would allow us to create an XML document that looked like this:

<item>
<shirt size="medium">Cotton</shirt>
</item>

We can also use a Schema to describe the same thing, an attribute called size that is an enumeration:

<xs:simpleType name="size_value">
 <xs:restriction base="xs:string">
  <xs:enumeration value="small"/>
  <xs:enumeration value="medium"/>
  <xs:enumeration value="large"/>
 </xs:restriction>
</xs:simpleType>
<xs:element name="shirt" type="xs:string">
 <xs:attribute name="size" type="size_value"/>
</xs:element>

But what if we wanted size to be an element? We can't do that with a DTD. DTDs do not provide for enumerations in an element's text content. However, because of datatypes with Schema, when we declared the enumeration in the preceding example, we actually created a simpleType called size_values which we can now use with an element:

<xs:element name="size" type="size_value">

That would allow us to use the following XML:

<item>
<shirt>
<size>medium</size>
</shirt>
</item>

This kind of flexibility is directly related to datatypes, but it is still one way in which XML Schema can be more flexible than DTDs.

When You Should Use a DTD

Just because the W3C built it does not mean you have to use it. There are times when it will be perfectly reasonable to stick with the DTD you are currently using. Obviously, if your DTD is functional and you don't have any need to extend it, then chances are you might be better off leaving well enough alone. But let's say that you are developing a schema from scratch. When should you use a DTD instead of an XML Schema? Here are a few examples.

When Brevity Matters

We mentioned before that DTDs tend to be more concise than XML Schema. XML in general is not designed for brevity; it is a verbose language, which is part of what helps make it more human-readable. So, if brevity is important, you might want to see if you can accomplish your goals with a DTD instead of a Schema. Need proof? Take a look at an example of a DTD and a Schema, side-by-side, which both define the same thing, a schema for a TV Listing.

The XML Document we are defining the schema for looks like this:

<listing>
<show>
<title>Frontline</title>
<cast>NA</cast>
<rating>TV-PG</rating>
<description>A PBS news/documentary</description>
<date>April 1, 2004</date>
<time>10pm EST</time>
</show>
</listing>

This is a very simple XML document. The root element is the <listing> element, which can contain multiple <show> elements, and the show must contain one each of the title, cast, rating, description, date, and time elements. Here is the DTD which would describe our TV Listing document:

<!ELEMENT listing (show*)>
<!ELEMENT show (title, cast, rating, description, date, time)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT cast (#PCDATA)>
<!ELEMENT rating (#PCDATA)>
<!ELEMENT description (#PCDATA)>
<!ELEMENT date (#PCDATA)>
<!ELEMENT time (#PCDATA)>

Because this example does not make use of any complex content models or even attributes, this is as straightforward as DTDs get. Let's take a look at the Schema that describes the exact same document:

<?xml version="1.0" encoding="UTF-8" ?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">

<element name="listing">
 <complexType>
 <sequence>
 <element name="show" maxOccurs="unbounded">
 <complexType>
  <sequence>
  <element name="title" type="string"/>
  <element name="cast" type="string"/>
  <element name="rating" type="string"/>
  <element name="description" type="string"/>
  <element name="date" type="string"/>
  <element name="time" type="string"/>
  </sequence>
 </complexType>
 </element>
 </sequence>
 </complexType>
</element>

</schema>

The Schema takes 22 lines of code to accomplish what the DTD accomplishes in 8 lines. Just comparing the two examples side-by-side shows that Schema are verbose, so if brevity is important to your needs, consider a DTD.

When You Want Users to Be Able to Override Definitions Easily

XML Schema use namespaces. In the previous chapter you saw how XML Schema use namespaces. Schema have one namespace declared for the Schema elements themselves (such as <element>) and another targetNamespace declared for the elements you are defining. With all of these namespaces floating about, it is easy to confuse them, or to create a namespace collision: a situation where there are conflicting references to a namespace. Practically speaking, that means that redefining elements using Schema can be complicated.

When would you want to redefine an element? Well, for example, if we defined an address element in an XML Schema, a user in the U.S. might want to redefine the element to conform to the U.S. address format, which includes a ZIP code:

John Doe
1023 Easy Street
New York, NY 10002

while a user in the U.K. won't use ZIP codes, but instead would use postal codes:

John Doe
2312 Kingsbury Way
Southhampton
Lincolnshire
3SW 1N2

With DTDs, redefining or overriding declarations can be pretty easy. It can be done within an external DTD using parameter entities, or it can be done in an internal DTD, contained within the DOCTYPE literal in an XML document. For example, the DOCTYPE declaration used to link an XML document to the DTD can also contain element declarations, attribute declarations, and so on, internally as well. If those internal DTD declarations are in conflict with the declarations in the external DTD, then the internal declarations are used.

Having both an internal DTD (contained in the XML document) and an external DTD (referenced in the document) makes it very easy to manipulate the DTD by extending or overriding the declarations. Of course, XML Schema have methods to import or include other XML Schema; however, doing so is not necessarily trivial, and in fact can be quite complex because of namespace issues that might arise from having two elements with the same name, and keeping track of the various namespaces elements belong to. So if you are using a base schema, but have the need to easily override or extend that schema, a DTD might be a better choice than XML Schema.

When You Have Mostly Text Documents

Everyone talks about the power of XML Schema, especially the power of datatypes. And it is true that datatypes offer a high degree of flexibility and power that was not possible before with DTDs. But not everyone needs that kind of flexibility and power. What if your needs center around large-scale documents which are mostly (if not entirely) text?

Some examples might include manuals, documentation, encyclopedias, and dictionaries. While these might have some elements used for indexing and cross-referencing, the majority of the elements might simply contain large blocks of text.

That's a perfect example of the type of document which might not benefit from an XML Schema. In fact, those types of documents might even benefit from DTD usage, since there are fewer differences between an XML and SGML DTD, and many document solutions were originally built around SGML, making it faster and easier to port an SGML DTD into and XML DTD than into an XML Schema.

If your uses for XML are mostly large blocks of text, then you might want to just stick with DTDs. Unless there is a compelling Schema feature which is essential to your document needs, chances are a DTD will satisfy your schema requirements adequately, and quite possibly more efficiently.

If Your Tools Don't Support Schema

You spend six months researching, designing, and writing the perfect XML Schema. It is a thing of beauty, designed to anticipate your every data need. It is compatible with your database Schema and it describes your XML document perfectly. It allows you to do things you could have never done with a DTD, and even though you don't need that functionality now, your foresight will pay off tenfold in the future. You are proud of your work.

And then you discover from your Web department that the parser it has chosen to use for implementing XML in conjunction with your Web site doesn't support XML Schema.

XML Schema are a fairly new technology. If the tools you rely upon everyday in order to be productive don't support XML Schema, then you might just have to stick to DTDs for a while. That doesn't mean you can't think about XML Schema, or learn how you might use them in the future. But in the meantime, if your software doesn't support XML Schema, it won't do you much good to use them.

  • + Share This
  • 🔖 Save To Your Account

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