Home > Articles > Web Services > XML

The DTD Synax

XML by Example teaches Web developers to make the most of XML with short, self-contained examples every step of the way. The book presumes knowledge of HTML, the Web, Web scripting, and covers such topics as: Document Type Definitions, Namespaces, Parser Debugging, XSL (Extensible Stylesheet Language), and DOM and SAX APIs. At the end, developers will review the concepts taught in the book by building a full, real-world e-commerce application.
This chapter is from the book

This chapter is from the book

The syntax for DTDs is different from the syntax for XML documents. Listing 3.1 is the address book introduced in Chapter 2 but with one difference: It has a new <!DOCTYPE> statement. The new statement is introduced in the section "Document Type Declaration." For now, it suffices to say that it links the document file to the DTD file. Listing 3.2 is its DTD.

Listing 3.1: An Address Book in XML

<?xml version="1.0"?> 
<!DOCTYPE address-book SYSTEM "address-book.dtd"> 
<!-- loosely inspired by vCard 3.0 --> 
    <name>John Doe</name>
      <street>34 Fountain Square Plaza</street>  
    <tel preferred="true">513-555-8889</tel>  
    <email href="mailto:jdoe@emailaholic.com"/>  
    <email href="mailto:jsmith@emailaholic.com"/>  

Listing 3.2: The DTD for the Address Book

<!-- top-level element, the address book is a list of entries --> 
<!ELEMENT address-book  (entry+)>  
<!-- an entry is a name followed by addresses, phone numbers, etc.--> 
<!ELEMENT entry  (name,address*,tel*,fax*,email*)>  
<!-- name is made of string, first name and last name. This is a very 
flexible model to accommodate exotic name       --> 
<!ELEMENT name   (#PCDATA | fname | lname)*> 
<!ELEMENT fname  (#PCDATA)> 
<!ELEMENT lname  (#PCDATA)>  
<!-- definition of the address structure if several addresses, the 
preferred attribute signals the "default" one   --> 
<!ELEMENT address      (street,region?,postal-code,locality,country)> 
<!ATTLIST address      preferred (true | false)  "false"> 
<!ELEMENT street       (#PCDATA)> <!ELEMENT region       (#PCDATA)> 
<!ELEMENT postal-code  (#PCDATA)> <!ELEMENT locality     (#PCDATA)> 
<!ELEMENT country      (#PCDATA)>   
<!-- phone, fax and email, same preferred attribute as address--> 
<!ELEMENT tel       (#PCDATA)> 
<!ATTLIST tel       preferred (true | false)  "false"> 
<!ELEMENT fax       (#PCDATA)> <!ATTLIST fax       
preferred (true | false)  "false"> 
<!ELEMENT email     EMPTY> 
<!ATTLIST email     href  CDATA               
#REQUIRED preferred (true | false)  "false"> 

Element Declaration

  1. DTD is a mechanism to describe every object (element, attribute, and so on) that can appear in the document, starting with elements. The following is an example of element declaration:

    <!ELEMENT address-book  (entry+)> 

    After the <!ELEMENT markup comes the element name followed by its content model. The element declaration is terminated with a right angle bracket.

    Element declarations are easy to read: The right side (the content model) defines the left side (the element name). In other words, the content model lists the children that are acceptable in the element.

    The previous declaration means that an address-book element contains one or more entry elements. address-book is on the left side, entry on the right. The plus sign after entry means there can be more than one entry element.

  2. Parentheses are used to group elements in the content model, as in the following example:

 <!ELEMENT name (lname, (fname | title))>

Element Name

As we saw in Chapter 2, XML names must follow certain rules. Specifically, names must start with either a letter or a limited set of punctuation characters ("_",":"). The rest of the name can consist of the same characters plus letters, digits and new punctuation characters (".", "-"). Spaces are not allowed in names.

Names cannot start with the string "xml," and as we will see in Chapter 4, "Namespaces," the colon plays a special role so it is advised you don't use it.

Special Keywords

For most elements, the content model is a list of elements. It also can be one of the following keywords:

  • #PCDATA stands for parsed character data and means the element can contain text. #PCDATA is often (but not always) used for leaf elements. Leaf elements are elements that have no child elements.

  • EMPTY means the element is an empty element. EMPTY always indicates a leaf element.

  • ANY means the element can contain any other element declared in the DTD. This is seldom used because it carries almost no structure information. ANY is sometimes used during the development of a DTD, before a precise rule has been written. Note that the elements must be declared in the DTD.

Element contents that have #PCDATA are said to be mixed content. Element contents that contain only elements are said to be element content. In Listing 3.2, tel is a leaf element that contains only text while email is an empty element:

<!ELEMENT tel    (#PCDATA)> <!ELEMENT email  EMPTY> 

Note that CDATA sections appear anywhere #PCDATA appears.

The Secret of Plus, Star, and Question Mark

The plus ("+"), star ("*"), and question mark ("?") characters in the element content are occurrence indicators. They indicate whether and how elements in the child list can repeat.

  • An element followed by no occurrence indicator must appear once and only once in the element being defined.

  • An element followed by a "+" character must appear one or several times in the element being defined. The element can repeat.

  • An element followed by a "*" character can appear zero or more times in the element being defined. The element is optional but, if it is included, it can repeat indefinitely.

  • An element followed by a "?" character can appear once or not at all in the element being defined. It indicates the element is optional and, if included, cannot repeat.

The entry and name elements have content model that uses an occurrence indicator:

<!ELEMENT entry    (name,address*,tel*,fax*,email*)> 
<!ELEMENT address  (street,region?,postal-code,locality,country)> 

Acceptable children for the entry are name, address, tel, fax, and email. Except for name, these children are optional and can repeat.

Acceptable children for address are street, region, postal-code, locality, and country. None of the children can repeat but the region is optional.

The Secret of Comma and Vertical Bar

The comma (",") and vertical bar ("|") characters are connectors. Connectors separate the children in the content model, they indicate the order in which the children can appear. The connectors are

  • the "," character, which means both elements on the right and the left of the comma must appear in the same order in the document.

  • the "|" character, which means that only one of the elements on the left or the right of the vertical bar must appear in the document.

The name and address elements are good examples of connectors.

<!ELEMENT name     (#PCDATA | fname | lname)*> 
<!ELEMENT address  (street,region?,postal-code,locality,country)> 

Acceptable children for name are #PCDATA or a fname element or a lname element. Note that it is one or the other. However, the whole model can repeat thanks to the "*" occurrence indicator.

Acceptable children for address are street, region, postal-code, locality, and country, in exactly that order.

The various components of mixed content must always be separated by a "|" and the model must repeat. The following definition is incorrect:

<!ELEMENT name  (#PCDATA, fname, lname)> 

It must be

<!ELEMENT name (#PCDATA | fname | lname)*> 

Element Content and Indenting

In the previous chapter, you learned that the XML application ignores indenting in most cases. Here again, a DTD can help.

If a DTD is associated with the document, then the XML processor knows that spaces in an element that has element content must indent (because the element has element content, it cannot contain any text). The XML processor can label the spaces as ignorable whitespaces. This is a very powerful hint to the application that the spaces are indenting.

Nonambiguous Model

The content model must be deterministic or unambiguous. In plain English, it means that it is possible to decide which part of the model applies to the current element by looking only at the current element.

For example, the following model is not acceptable:

<!ELEMENT cover  ((title, author) | (title, subtitle))> 

because when the XML processor is reading the element

<title>XML by Example</title> 


  <title>XML by Example</title>
  <author>Benoît Marchal</author>

it cannot decide whether the title element is part of (title, author) or of (title, subtitle) by looking at title only. To decide that title is part of (title, author), it needs to look past title to the author element.

In most cases, however, it is possible to reorganize the document so that the model becomes acceptable:

<!ELEMENT cover  (title, (author | subtitle))> 

Now when the processor sees title, it knows where it fits in the model.


Attributes also must be declared in the DTD. Element attributes are declared with the ATTLIST declaration, for example:

<!ATTLIST tel  preferred (true | false)  "false"> 

The various components in this declaration are the markup (<!ATTLIST), the element name (tel), the attribute name (preferred), the attribute type ((true | false)), a default value ("false"), and the right angle bracket.

For elements that have more than one attribute, you can group the declarations. For example, email has two attributes:

<!ATTLIST email  href      CDATA           
#REQUIRED preferred (true | false)  "false"> 

Attribute declaration can appear anywhere in the DTD. For readability, it is best to list attributes immediately after the element declaration.


If used in a valid document, the special attributes xml:space and xml:lang must be declared as


xml:space (default|preserve) "preserve"

The DTD provides more control over the content of attributes than over the content of elements. Attributes are broadly divided into three categories:

  • string attributes contain text, for example:

    	<!ATTLIST email  href CDATA #REQUIRED> 
  • tokenized attributes have constraints on the content of the attribute, for example:

    	<!ATTLIST entry id ID #IMPLIED> 
  • enumerated-type attributes accept one value in a list, for example:

    <!ATTLIST entry preferred (true | false) "false">

Attribute types can take any of the following values:

  • CDATA for string attributes.

  • ID for identifier. An identifier is a name that is unique in the document.

  • IDREF must be the value of an ID used elsewhere in the same document. IDREF is used to create links within a document.

  • IDREFS is a list of IDREF separated by spaces.

  • ENTITY must be the name of an external entity; this is how you assign an external entity to an attribute.

  • ENTITIES is a list of ENTITY separated by spaces.

  • NMTOKEN is essentially a word without spaces.

  • NMTOKENS is a list of NMTOKEN separated by spaces.

  • Enumerated-type list is a closed list of nmtokens separated by |, the value has to be one of the nmtokens. The list of tokens can further be limited to NOTATIONs (introduced in the section "Notation," later in this chapter).

Optionally, the DTD can specify a default value for the attribute. If the document does not include the attribute, it is assumed to have the default value. The default value can take one of the four following values:

  • #REQUIRED means that a value must be provided in the document

  • #IMPLIED means that if no value is provided, the application must use its own default

  • #FIXED followed by a value means that attribute value must be the value declared in the DTD

  • A literal value means that the attribute will take this value if no value is given in the document.


Information that remains constant between documents is an ideal candidate for #FIXED attributes. For example, if prices are always given in dollars, you could declare a price element as

<!ELEMENT price (#PCDATA)> 
<!ATTLIST price currency NMTOKEN #FIXED "usd"> 


When the application reads



in a document, it appears as though it reads

<price currency="usd">19.99</price> 


The application has received additional information but it didn't require additional markup in the document!

Document Type Declaration

The document type declaration attaches a DTD to a document. Don't confuse the document type declaration with the document type definition (DTD). The document type declaration has the form:

<!DOCTYPE address-book SYSTEM "address-book.dtd"> 

It consists of markup (<!DOCTYPE), the name of the top-level element (address-book), the DTD (SYSTEM "address-book.dtd") and a right angle bracket. As Listing 3.1 illustrates, the document type declaration appears at the beginning of the XML document, after the XML declaration.

The top-level element of the document is selected in the declaration. Therefore, it is possible to create a document starting with any element in the DTD. Listing 3.3 has the same DTD as Listing 3.1, but its top-level element is an entry.

Listing 3.3: An Entry

<?xml version="1.0"?> 
<!DOCTYPE entry SYSTEM "address-book.dtd"> 
  <name>John Doe</name>  
    <street>34 Fountain Square Plaza</street>  
  <tel preferred="true">513-555-8889</tel>  
  <email href="mailto:jdoe@emailaholic.com"/>  

Internal and External Subsets

The DTD is divided into internal and external subsets. As the name implies, the internal subset is inserted in the document itself, whereas the external subset points to an external entity.

The internal and the external subsets have different rules for parameter entities. The differences are explained in the section "General and Parameter Entities," later in this chapter.

The internal subset of the DTD is included between brackets in the document type declaration. The external subset is stored in a separate entity and referenced from the document type declaration.

The internal subset of a DTD is stored in the document, specifically in the document type declaration, as in

<!DOCTYPE address [ 
<!ELEMENT address  (street,region?,postal-code,locality,country)> 
<!ATTLIST address  preferred (true | false)  "false">  
<!ELEMENT street       (#PCDATA)> 
<!ELEMENT region       (#PCDATA)> 
<!ELEMENT postal-code  (#PCDATA)> 
<!ELEMENT locality     (#PCDATA)> 
<!ELEMENT country      (#PCDATA)> ]> 

The external subset is not stored in the document. It is referenced from the document type declaration through an identifier as in the following examples:

<!DOCTYPE address-book SYSTEM "http://www.xmli.com/dtd/address-book.dtd">  
<!DOCTYPE address-book PUBLIC "-//Pineapplesoft//Address Book//EN" 
<!DOCTYPE address-book SYSTEM "../dtds/address-book.dtd"> 

There are two types of identifiers: system identifiers and public identifiers. A keyword, respectively SYSTEM and PUBLIC, indicates the type of identifier.

  • A system identifier is a Universal Resource Identifier (URI) pointing to the DTD. URI is a superset of URLs. For all practical purposes, a URI is a URL.

  • In addition to the system identifier, the DTD identifier might include a public identifier. A public identifier points to a DTD recorded with the ISO according to the rules of ISO 9070. Note that a system identifier must follow the public identifier.

The system identifier is easy to understand. The XML processor must download the document from the URI.

Public identifiers are used to manage local copies of DTDs. The XML processor maintains a catalog file that lists public identifiers and their associated URIs. The processor will use these URIs instead of the system identifier.

Obviously, if the URIs in the catalog point to local copies of the DTD, the XML processor saves some downloads.

Listing 3.4 is an example of a catalog file.

Listing 3.4: A Catalog File

  <Base HRef="http://catwoman.pineapplesoft.com/dtd/"/> 
  <Map PublicId="-//Pineapplesoft//Address Book//EN" HRef="address-book.dtd"/> 
  <Map PublicId="-//Pineapplesoft//Article//EN" HRef="article.dtd"/> 
  <Map PublicId="-//Pineapplesoft//Simple Order//EN" HRef="order.dtd"/> 
  <Extend Href="http://www.w3.org/xcatalog/mastercat.xml"/> 

Finally, note that a document can have both an internal and an external subset as in

<!DOCTYPE address SYSTEM "address-content.dtd" [ 
<!ELEMENT address  (street,region?,postal-code,locality,country)> 
<!ATTLIST address  preferred (true | false)  "false"> ]>  

Public Identifiers Format

The following public identifiers point to the address book:

"-//Pineapplesoft//Address Book//EN" 

There are four parts, separated by "//":

  • The first character is + if the organization is registered with ISO, - otherwise (most frequent).

  • The second part is the owner of the DTD.

  • The third part is the description of the DTD; spaces are allowed.

  • The final part is the language (EN for English).

Standalone Documents

As you have seen, the DTD not only describes the document, but it can affect how the application reads the document. Specifically, default and fixed attribute values will add information to the document. Entities, which are also declared in the DTD, modify the document.

If all the entries that can influence the document are in the internal subset of the DTD, the document is said to be standalone. In other words, an XML processor does not need to download external entities to access all the information (it might have to download external entities to validate the document but that does not impact the content).

Conversely, if default attribute values or entities are declared in the external subset of the document, then the XML processor has to read the external subset, which might involve downloading more files.

Obviously, a standalone document is more efficient for communication over a network because only one file needs to be downloaded. The XML declaration has an attribute, standalone, that declares whether the document is a standalone document or not. It accepts only two values: yes and no. The default is no.

<?xml version="1.0" standalone="yes"?> 

Note that a standalone document might have an external DTD subset but the external subset cannot modify how the application reads the document. Specifically, the external subset cannot

  • declare entities

  • declare default attribute values

  • declare element content if the elements include spaces, such as for indenting. The last rule is the easiest to break but it is logical: If the DTD declares element content, then the processor reports indenting as ignorable whitespaces; otherwise, it reports as normal whitespaces.

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.


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.


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.


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.


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


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


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.


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.


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