Lesson 6 — Validation

DTD (Document Type Definition)

A DTD defines the legal building blocks of an XML document — which elements and attributes are allowed, and how they can be structured together.

Defining a Simple DTD

A DTD can be included directly in a document or linked externally. It declares each element and the elements or text it's allowed to contain.

XML — An inline DTD
<?xml version="1.0"?>
<!DOCTYPE student [
  <!ELEMENT student (name, age, course)>
  <!ELEMENT name (#PCDATA)>
  <!ELEMENT age (#PCDATA)>
  <!ELEMENT course (#PCDATA)>
]>
<student>
  <name>Ayesha Patel</name>
  <age>23</age>
  <course>XML</course>
</student>

Common Mistakes

  • Getting the declared element order wrong in the DTD compared to the actual document — DTDs enforce sequence strictly by default.
  • Forgetting #PCDATA for elements that hold plain text content.
  • Assuming DTDs support the same rich data typing as XML Schema — DTDs are far more limited, with no real concept of numbers vs text.
  • Not realising DTDs use their own distinct syntax, separate from regular XML markup.

Professional Tip

DTDs were XML's original validation mechanism and are still found in many legacy systems, but XML Schema (XSD, covered next) has largely replaced them for new projects due to its richer typing and full XML-based syntax.

Your Turn

Write a DTD for a <book> element requiring title, author, and year child elements, then write an XML document that validates against it.

Mini Quiz

What is the main purpose of a DTD in XML?