DTD Fundamentals: Elements, Attributes, and Validation

Unit 2â€ĸCLO02

Learning Objectives

Course Learning Outcomes

CLO02

Course Outcomes

CO02
â„šī¸

Introduction

A DTD is the original grammar for XML. It lists which elements exist, how they nest, and which attributes are allowed. Even if XSD is richer, DTD fluency is essential for legacy systems and exam answers.

Study tracker

Mark what you have completed for this topic.

0% done

The Basics

What a DTD captures

  • Allowed elements and their order.
  • Cardinality using ?, *, +.
  • Allowed attributes with types (CDATA, ID, IDREF, enumerations).
  • Entities for reusable text.

Internal vs external

  • Internal: rules declared inside the DOCTYPE.
  • External: referenced with system/public identifiers for reuse.

Technical Details

Element and attribute declarations

<!ELEMENT library (book+)>
<!ELEMENT book (title, author, price)>
<!ELEMENT title (#PCDATA)>
<!ATTLIST book id ID #REQUIRED>
<!ATTLIST book category (cs|ee|me) "cs">

Operators recap: ? optional, * zero-or-more, + one-or-more, | choice, comma = sequence.

Examples

Library with internal DTD

<?xml version="1.0"?>
<!DOCTYPE library [
  <!ELEMENT library (book+)>
  <!ELEMENT book (title, author, price)>
  <!ATTLIST book id ID #REQUIRED>
  <!ELEMENT title (#PCDATA)>
  <!ELEMENT author (#PCDATA)>
  <!ELEMENT price (#PCDATA)>
]>
<library>
  <book id="b1">
    <title>XML</title>
    <author>John</author>
    <price>499</price>
  </book>
</library>

Self-check

Real-World Use

Hands-on

  • Draft a DTD for a course catalog with course, credits, faculty.
  • Validate one XML sample, then break rules (wrong order, missing attribute) to see error messages.
  • Move rules to an external DTD and reference it from your XML.

📝 For exams

Exam prep

  • Define #PCDATA and EMPTY.
  • Write one element declaration using + and |.
  • Sketch a DOCTYPE for an employee file with required id attribute.

✨ Key points

Takeaways

  • DTD gives structural validation but almost no data typing.
  • Keep content models simple; deeply nested choices become unreadable.
  • External DTDs promote reuse across documents.