XML DTD

A 'well-formed' XML document is one that is grammatically correct.

An XML document validated by DTD is both 'well-formed' and 'valid'.

What is DTD?

DTD Represents Document Type Definition (Document Type Definition).

DTD Define the structure of XML documents, as well as the valid elements and attributes.

Valid XML document

A 'valid' XML document is both 'well-formed' and conforms to the rules of DTD:

<?xml version="1.0" encoding="UTF-8"?>
!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

The above DOCTYPE declaration includes a reference to the DTD file. Below is the content of the DTD file and its explanation.

XML DTD

The purpose of DTD is to define the structure of XML documents, as well as the valid elements and attributes:

Note.dtd:

!DOCTYPE note
[
!ELEMENT note (to,from,heading,body)
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>

The above DTD is explained as follows:

!DOCTYPE note - Define the root element of the document as note
!ELEMENT note - Define that the note element must contain the following elements: "to, from, heading, body"
!ELEMENT to - Define the to element as the "#PCDATA" type
!ELEMENT from - Define the from element as the "#PCDATA" type
!ELEMENT heading - Define the heading element as the "#PCDATA" type
!ELEMENT body - Define the body element as the "#PCDATA" type

Tip:#PCDATA represents parseable character data (parseable character data).

Entity declaration using DTD

The DOCTYPE declaration can also be used to define special characters or strings used in the document:

Example

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note [
<!ENTITY nbsp " ">
<!ENTITY writer "Writer: Bill Gates.">
<!ENTITY copyright "Copyright: CodeW3C.com.">
]>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
<footer>&writer; ©right;</footer>
</note>

Tip:An entity consists of three parts: starting with an ampersand (&), followed by the entity name, and ending with a semicolon (;).

When to use DTD?

With DTD, independent groups can reach an agreement on the standard for exchanging data.

With DTD, you can validate whether the data received from the outside world is valid.

You can also use DTD to validate your own data.

If you want to learn about DTD, please read our DTD Tutorial.

When not to use DTD?

DTD is not necessary for XML.

If you are testing XML or using very small XML files, creating DTD may be a waste of time.

If you are developing an application, wait until the specification is stable before adding DTD. Otherwise, your software may stop working due to validation errors.