XML DTD 

In this tutorial, the basic concept of XML Document Type Definition (DTD) is described. The objective of a DTD is to define the structure of an XML document. It basically defines the structure with a list of legal elements such as Elements, Attributes, Entities, PCDATA (parsed character data) and CDATA (character data).

A “valid” XML document is a “well-formed” XML document, which also conforms to the rules of a Document Type Definition (DTD). This defines the elements that may be included in our XML document, what attributes these elements have, and the ordering and nesting of the elements. A DTD can be defined internally inside an XML document, or as an external reference. External DTDs usually have the filename extension “.dtd“.

 

1) External DTD:

The following example shows an external DTD called “book.dtd“.

<!ELEMENT book (title, author, info, body)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT info (#PCDATA)>
<!ELEMENT body (#PCDATA)>

The DTD above is interpreted like this:

  • !DOCTYPE book defines that the root element of this document is note
  • !ELEMENT book defines that the note element contains four elements: “title, author, info, body”
  • !ELEMENT title defines the to element  to be of type “#PCDATA”
  • !ELEMENT author defines the from element to be of type “#PCDATA”
  • !ELEMENT info defines the heading element to be of type “#PCDATA”
  • !ELEMENT body defines the body element to be of type “#PCDATA”

If the above DTD is declared in an external file, it should be wrapped in a DOCTYPE definition with the following syntax:

<!DOCTYPE root-element SYSTEM "filename">

The following example shows an XML document with the external DTD mentioned above:

<?xml version="1.0" encoding="UTF-8”?>
<!DOCTYPE book SYSTEM "book.dtd">
<book>
  <title>Great Stories for Children</title>
  <author>Ruskin Bond</author>
  <info>This book is for children.</info>
  <body>It is a collection of author's most delightful children's stories​.</body>
</book>

 

2) Internal DTD:

The following example shows an internal DTD. It should be wrapped in a DOCTYPE definition with the following syntax:

<!DOCTYPE root-element [element-declarations]>

Example XML document with an internal DTD:

<?xml version="1.0" encoding="UTF-8”?>
<!DOCTYPE book [
<!ELEMENT book (title, author, info, body)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT info (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<book>  <title>Great Stories for Children</title>   <author>Ruskin Bond</author>   <info>This book is for children.</info>   <body>It is a collection of author's most delightful children's stories​.</body> </book>

The next section shows the basic building blocks of XML documents from a DTD point of view.