DTD Fundamentals: Elements, Attributes, and Validation
Unit 2âĸCLO02
Learning Objectives
Course Learning Outcomes
CLO02
Course Outcomes
CO02
âšī¸
Introduction
DTD (Document Type Definition) defines the allowed structure of an XML document. A DTD acts as a contract: which elements can appear, in what order, how many times, and with what attributes. While many modern systems prefer XSD, DTD remains important for legacy systems and for understanding validation.
The Basics
What a DTD specifies
A DTD can define:
- allowed elements and their content models
- allowed attributes and their types
- entities (reusable text)
Internal vs external DTD
- Internal: inside
<!DOCTYPE ... [ ... ]> - External: referenced via system/public identifiers
Technical Details
Core declarations
Element declarations
<!ELEMENT library (book+)>
<!ELEMENT book (title, author, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
Operators:
?optional*zero or more+one or more|choice- , sequence
Attribute list
<!ATTLIST book id ID #REQUIRED>
<!ATTLIST book category (cs|ee|me) "cs">
Examples
Example: XML + 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>
Real-World Use
Practical
- Write XML and DTD for
library. - Test errors:
- remove a required element
- change order
- remove a required attribute
đ For exams
Exam
- Define DTD and #PCDATA.
- Explain internal vs external DTD.
- Design a DTD for a simple application.
⨠Key points
Takeaways
- DTD provides a grammar for XML structure.
- It validates ordering and occurrence but has limited datatypes.