A Document Type Definition (DTD) defines the legal building blocks of an XML document. It defines the document structure with a list of legal elements and attributes.
<!DOCTYPE root-element [element-declarations]>
Example XML document with an internal DTD:
Or with an internal DTD:
The DTD above is interpreted like this:
!DOCTYPE note defines that the root element of this document is note.
!ELEMENT note defines that the note element contains four elements: "to,from,heading,body".
!ELEMENT to defines the to element to be of the type "#PCDATA".
!ELEMENT from defines the from element to be of the type "#PCDATA".
!ELEMENT heading defines the heading element to be of the type "#PCDATA".
!ELEMENT body defines the body element to be of the type "#PCDATA".
PCDATA is text that WILL be parsed by a parser. The text will be examined by the parser for entities and markup.
CDATA is text that will NOT be parsed by a parser
Declaring Elements
<!ELEMENT element-name (element-content)>
Empty Elements
<!ELEMENT element-name EMPTY>
Example:<!ELEMENT br EMPTY>
XML example:<br />
Elements with Parsed Character Data
<!ELEMENT element-name (#PCDATA)>
Example:<!ELEMENT from (#PCDATA)>
Elements with any Contents
<!ELEMENT element-name ANY>
Example:<!ELEMENT note ANY>
Elements with Children (sequences)
<!ELEMENT element-name (child1)> only one
<!ELEMENT element-name (child1+)> minimum one
<!ELEMENT element-name (child1*)> zero or more
<!ELEMENT element-name (child1?)> zero or one
<!ELEMENT element-name (child1,child2,...)>
Example:<!ELEMENT note (to,from,heading,body)>
<!ELEMENT note (to,from,(heading|body))>
Declaring Attributes
<!ATTLIST element-name attribute-name attribute-type default-value>
DTD example:<!ATTLIST payment type CDATA "check">
XML example:<payment type="check" />
Type | Description |
---|---|
CDATA |
The value is character data |
(en1|en2|..) |
The value must be one from an enumerated list |
ID |
The value is a unique id |
IDREF |
The value is the id of another element |
IDREFS |
The value is a list of other ids |
NMTOKEN |
The value is a valid XML name |
NMTOKENS |
The value is a list of valid XML names |
ENTITY |
The value is an entity |
ENTITIES |
The value is a list of entities |
NOTATION |
The value is a name of a notation |
xml: |
The value is a predefined xml value |
Value | Explanation |
---|---|
value |
The default value of the attribute |
#REQUIRED |
The attribute is required |
#IMPLIED |
The attribute is not required |
#FIXED value |
The attribute value is fixed |
An External Entity Declaration
<!ENTITY entity-name SYSTEM "URI/URL">
DTD Example:
<!ENTITY writer SYSTEM "http://www.w3schools.com/entities.dtd">
<!ENTITY copyright SYSTEM "http://www.w3schools.com/entities.dtd">
XML example:<author>&writer;©right;</author>
TV Schedule DTD