Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Introduction to DTD


May 28, 2021 DTD


Table of contents


Introduction to DTD


DTD, known as Document Type Definition, Chinese translated into document type definitions, is a set of syntax rules about markers established for data exchange between programs.

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

DTDs can be declared in rows in XML documents 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 using the following syntax:

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

An instance of an XML document with DTD (open it in IE5 and later and choose to view the source code):

<?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 Code command.

The DTD above is interpreted like this:

  • ! DOCTYPE note (second line) defines this document as a note type document.
  • ! ELstrongENT note (third line) defines note elements as having four elements: "to, from, heading, body"
  • ! ELstrongENT to (fourth row) defines the to element as the "#PCDATA" type
  • ! ELstrongENT from (fifth line) defines the frome element as the "#PCDATA" type
  • ! ELstrongENT heading (line 6) defines the heading element as the "#PCDATA" type
  • ! ELstrongENT body (line 7) defines the body element as the "#PCDATA" type

External document declaration

If the DTD is 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 Code 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 .dtd DTD:

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

Why use DTD?

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

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

Your application can also use a standard DTD to validate data received externally.

You can also use DTD to validate your own data.


Related tutorials

XML tutorial