Skip to main content

XML Document Type Declaration (DTD)

The XML Document Type Declaration (DTD) is used to formally describe the grammar of XML documents. In this way, an XML document can be a valid XML document.

What is a DTD and what is it used for?

DTD stands for Document Type Definition and it defines the structure, the elements and attributes of an XML document.

An application can use a DTD to verify if a given XML data is valid.

Should I use a DTD?

It depends on what you want to do:

  • YES, if you want to verify that the data is valid against the DTD. For example, you can verify that the data you received from a server is valid.

  • NO, if you are experimenting with XML or you have small XML files and you don't have time to create DTDs.

Well-formed and Valid XML Documents

  • An XML document is called well-formed if its syntax is correct.
  • An XML document is called valid if it is well-formed and it is validated against a DTD.

Example of Internal DTD Declaration

<?xml version="1.0"?>  
<!DOCTYPE book [
<!ELEMENT book (title,author,publisher)>
<!ELEMENT title(#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT publisher(#PCDATA)>
]>

<book>
<title>A Great Book</title>
<author>Tom Nolan</author>
<publisher>Tutorial Reference</publisher>
</book>

The DTD above is interpreted in this way:

  • !DOCTYPE book defines that the root element of the document is book
  • !ELEMENT book defines that the note element must contain the elements: title, author, publisher
  • !ELEMENT title defines the title element to be of type #PCDATA
  • !ELEMENT author defines the author element to be of type #PCDATA
  • !ELEMENT publisher defines the publisher element to be of type #PCDATA

Example of External DTD Declaration

The following example is a well-formed and valid XML document with book.dtd DTD reference defined in <!DOCTYPE>

book.xml
<?xml version="1.0"?>  
<!DOCTYPE book SYSTEM "book.dtd">
<book>
<title>A Great Book</title>
<author>Tom Nolan</author>
<publisher>Tutorial Reference</publisher>
</book>

The book.dtd is the following:

book.dtd
<!ELEMENT book (title,author,publisher)>
<!ELEMENT title(#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT publisher(#PCDATA)>