Dtd in XML
DTD in XML (Document Type Definition)
What is DTD?
DTD (Document Type Definition) defines the structure and legal elements and attributes of an XML document.
It acts like a schema or blueprint for your XML, specifying:
What elements can appear
Their order and hierarchy
Allowed attributes and their types
Whether elements or attributes are optional or required
Why Use DTD?
To validate an XML document’s structure.
To ensure the XML follows specific rules.
To help parsers check correctness before processing.
DTD Types
Internal DTD: Defined inside the XML document.
External DTD: Defined in a separate file and linked from XML.
Internal DTD Example
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE note [ <!ELEMENT note (to, from, heading, body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)>]><note> <to>John</to> <from>Jane</from> <heading>Reminder</heading> <body>Don't forget the meeting tomorrow!</body></note>External DTD Example
DTD file (note.dtd):
<!ELEMENT note (to, from, heading, body)><!ELEMENT to (#PCDATA)><!ELEMENT from (#PCDATA)><!ELEMENT heading (#PCDATA)><!ELEMENT body (#PCDATA)>XML file linking external DTD:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE note SYSTEM "note.dtd"><note> <to>John</to> <from>Jane</from> <heading>Reminder</heading> <body>Don't forget the meeting tomorrow!</body></note>Key DTD Declarations
| Declaration | Description | Example |
|---|---|---|
<!ELEMENT> | Defines an element and its content | <!ELEMENT book (title, author)> |
<!ATTLIST> | Defines attributes for elements | <!ATTLIST book id ID #REQUIRED> |
#PCDATA | Parsed character data (text content) | <title>XML Basics</title> |
#REQUIRED | Attribute must be provided | id attribute is required |
#IMPLIED | Attribute is optional | |
| ` | ` | OR choice between elements |
* | Zero or more occurrences | (chapter)* |
+ | One or more occurrences | (author)+ |
? | Zero or one occurrence (optional) | (subtitle)? |
Summary
DTD ensures your XML documents are consistent and follow a defined structure.
Can be internal or external.
Defines elements, their order, content, and attributes.
Helps in validation before processing XML data.
If you'd like, I can show you how to validate an XML against a DTD using tools or code!