DTD Introduction


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

A DTD can be declared inline in an XML document, or it can be referenced 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 using the following syntax:

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

XML document example with a 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>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 the "View Source" command.

The above DTD is explained as follows:

  • !DOCTYPE note(Line 2) defines that this document isnoteDocumentation of types.
  • !ELEMENT note(Third line) DefinitionnoteThe element has four elements: "to, from, heading, body".
  • !ELEMENT to(Fourth line) DefinitiontoThe element is of type "#PCDATA".
  • !ELEMENT from(Fifth line) DefinitionfromThe element is of type "#PCDATA".
  • !ELEMENT heading(Sixth line) DefinitionheadingThe element is of type "#PCDATA".
  • !ELEMENT body(Seventh line) DefinitionbodyThe element is of type "#PCDATA".

External document declaration

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

<!DOCTYPE root-element SYSTEM "filename">

This XML document is the same as the XML document above, but has an external DTD: (Click to open the file, and select the "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 containing the DTD:

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


Why use a DTD?

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

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

And your application can also use a standard DTD to validate data received from external sources.

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

other extensions