What is a DTD and what is it used for?

A Document Type Definition (DTD) defines the elements or record structure of a XML document. A DTD allows your XML files to carry a description of its format with it. The DTD for the above XML example looks like this:

<?xml version="1.0"?>

<!ELEMENT faq-list (question+)>
   <!ELEMENT question (query, response*)>
      <!ELEMENT query    (#PCDATA)>
      <!ELEMENT response (#PCDATA)>

Notes:

  • #PCDATA (parsed character data) means that the element contains data that can be parsed by a parser like HTML
  • The + sign in the example above declares that the "QUESTION" element must occur one or more times inside the "FAQ-LIST" element.
  • The * sign in the example above declares that the "QUERY" element can occur zero or more times inside the "QUESTION" element.

The W3C also formulated a new standard, called XML Schemas that superceded DTD's. Schemas allow for more complex data types within your tags and better ways to constrain (validate) data within these tags.