DTD Tutorial

Document Type Definition (DTD) can define the building blocks of a valid XML document. It uses a set of valid elements to define the structure of the document.

DTD can be declared inline in an XML document or as an external reference.

Internal DOCTYPE declaration

If the DTD is included in your XML source file, it should be wrapped in a DOCTYPE declaration as follows:

!DOCTYPE root-element [element declarations]>

XML document instance with DTD (Please open in IE5 and higher versions, and select View Source):

<?xml version="1.0"?>
!DOCTYPE note [
  !ELEMENT note (to,from,heading,body)
  !ELEMENT to      (#PCDATA)
  !ELEMENT from    (#PCDATA)
  !ELEMENT heading (#PCDATA)
  !ELEMENT body    (#PCDATA)
>
<note>
  <to>George</to>
  <from>John</from>
  <heading>Reminder</heading>
  <body>Don't forget the meeting!</body>
</note>

Open this XML file in your browser and select the "View Source" command.

The following DTD explanations are as follows:

!DOCTYPE note (Line 2) defines this document as note document type.

!ELEMENT note (Line 3) definition note The element has four elements: "to, from, heading, body"

!ELEMENT to (Line 4) definition to Elements of type "#PCDATA"

!ELEMENT from (Line 5) definition from Elements of type "#PCDATA"

!ELEMENT heading (Line 6) definition heading Elements of type "#PCDATA"

!ELEMENT body (Line 7) definition body Elements of type "#PCDATA"

External document declaration

If the DTD is located outside the XML source file, it should be enclosed in a DOCTYPE definition with the following syntax:

!DOCTYPE root-element SYSTEM "filename">

This XML document is the same as the above XML document, but it has an external DTD: (Open in IE5and select the "View Source" command.)

<?xml version="1.0"?>
!DOCTYPE note SYSTEM "note.dtd"
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

This is the "note.dtd" file containing the DTD:

!ELEMENT note (to,from,heading,body)
!ELEMENT to (#PCDATA)
!ELEMENT from (#PCDATA)
!ELEMENT heading (#PCDATA)
!ELEMENT body (#PCDATA)

Why Use DTD?

Through DTD, each of your XML files can carry a description of its own format.

Through DTD, independent groups can use a standard DTD to exchange data consistently.

And your application can also use a standard DTD to validate data received from the outside.

You can also use DTD to validate your own data.