An Introduction to DTD
K. Yue, copyright 2000,
November 22, 2000

Introduction

Example

Consider the XML document:

<person>
<name>Adam</name>
<spouse>M3774</spouse>
<spouse>Eva</spouse>
</person>

Potential questions:

Example:

A better approach is to specify the constraints using DTD.

A possible DTD declaration for this:

<!ELEMENT person (name, pet+)>
<!ATTLIST person
          id ID #REQUIRED
          spouse IDREF #IMPLIED>

An XML document satisfying the DTD:

<person id="p12324" spouse="p10001">
<name>Adam</name>
<pet>Eva</pet>
</person>
<person id="p10001">
<name>M3774</name>
</person>

DTD Declarations

Element Declarations

Example:

<!ELEMENT name (first, middleinitial?, last)>

OK:

<name><first>Bun</first><last>Yue</last></name>

Not OK:

<name><last>Yue</last><first>Bun</first ></name>
<name>The one and only:
<middleinitial>K</middleinitial>
<first>Bun</first><last>Yue</last></name>

Example:

Can you spot the potential implications?

<!ELEMENT bookcollection (book+) >
<!ELEMENT book (author, publisher, ISBN, chapter*)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT ISBN (#PCDATA)>
<!ELEMENT chapter (#PCDATA)>
<!ELEMENT bookcollection (book+) >
<!ELEMENT book (author, publisher, ISBN, chapter*)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT ISBN (#PCDATA)>
<!ELEMENT chapter (#PCDATA)>

ATTList Declarations

Example:

<!ATTLIST person
    comment CDATA #IMPLIED>
<!ATTLIST person
    ssn ID #REQUIRED
    gender (male|female) #IMPLIED
    age NMTOKEN #IMPLIED
    iq NMTOKEN "100">

OK:

<person ssn="123456789">…
</person>
<person ssn="111-11-1111"
  gender="female" iq="200">…</person>
<person ssn="abc">…</person>

Not OK:

<person>…</person>
<person ssn="123" gender="unknown">…</person>
<person ssn="123" age="???">…</person>

Example:

simpleAddress.DTD

<!ELEMENT addressBook (person)+>
<!ELEMENT person (name,email*,link?)>
<!ATTLIST person id ID #REQUIRED>
<!ATTLIST person
    gender (male|female) #IMPLIED
    luckynumber (NMTOKENS) #IMPLIED>
<!ELEMENT name (#PCDATA|(first,last))|(last,first))>
<!ELEMENT first (NMTOKEN)>
<!ELEMENT last (#PCDATA)>
<!ELEMENT email (#PCDATA)>
<!ELEMENT link EMPTY>
<!ATTLIST link
    spouse IDREF #IMPLIED
    children IDREFS #IMPLIED>

An XML document satisfying the DTD:

<?xml version="1.0"?>
<!DOCTYPE addressBook SYSTEM "http://yourserver/dtd/addressBook.dtd">
<addressBook>
<person id="123456789" gender="male" luckynumber="7 12 3">
  <name>
    <last>Hope</last> <first>Bob</first>
  </name>
  <email>BobHope@hollywood.com</email>
</person>
<person id="222222222" gender="female">
  <name>Deborah King</name>
  <link spouse="222222223" children="222222226 222222227" />
</person>
<person id="222222223" gender="male">
  <name>Jim King</name>
</person>
<person id="222222226" gender="male">
  <name>John King</name>
</person>
<person id="222222227" gender="female">
  <name>Jane King</name>
</person>
</addressBook>