Latest web development tutorials

Introduction to DTD

Document Type Definition (DTD) to define the legal building blocks of an XML document. It uses a series of legal elements to define the structure of the document.

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


Internal DOCTYPE declaration

If the DTD is included in your XML source file, it should adopt the following syntax wrapped in a DOCTYPE declaration:

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

XML document instance with the DTD (please IE5 and higher versions of Open 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>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend</body>
</note>

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

The DTD above is interpreted like this:

  • ! DOCTYPE note (second line) is defined in this document is note type of document.
  • ! ELstrongENT note (third row) definitions note element has four elements: "to, from, heading ,, body"
  • ! ELstrongENT to (the fourth line) to define elements "#PCDATA" type
  • ! ELstrongENT from (fifth row) is defined frome element "#PCDATA" type
  • ! ELstrongENT heading (sixth row) element as defined heading "#PCDATA" type
  • ! ELstrongENT body (seventh row) is defined as a body element "#PCDATA" type

External document declaration

If the DTD is located in an external XML source files, then it should be wrapped in a DOCTYPE definition with the following syntax:

<!DOCTYPE root-element SYSTEM "filename">

This is the same XML documents and XML document above, but does have an external DTD: ( click to open the file and select "View Source" command.)

<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

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

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


Why use a DTD?

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

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

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

You can also use a DTD to verify your own data.