Introduction to DTD
The purpose of a DTD is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements. A DTD can be declared inline in your XML document, or as an external reference.
Internal DTD
This is an XML document with a Document Type Definition: (Open
it in IE5, and select view source)
<?xml version="1.0"?> <!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> |
The DTD is interpreted like this:
!ELEMENT note (in line 2) defines the element “note” as having
four elements: “to,from,heading,body”.
!ELEMENT to (in line 3) defines the “to” element to be of
the type “CDATA”.
!ELEMENT from (in line 4) defines the “from” element to be of the
type “CDATA”
and so on…..
External DTD
This is the same XML document with an external DTD: (Open
it in IE5, and select view source)
<?xml version="1.0"?> <!DOCTYPE note SYSTEM "note.dtd"> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> |
This is a copy of the file “note.dtd” containing the Document
Type Definition:
<?xml version="1.0"?> <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> |
Why use a DTD?
XML provides an application independent way of sharing data. With a DTD, independent groups of people can agree to use a common DTD for interchanging data. Your application can use a standard DTD to verify that data that you receive from the outside world is valid. You can also use a DTD to verify your own data.
A lot of forums are emerging to define standard DTDs for almost everything in the areas of data exchange. Take a look at: CommerceNet’s XML exchange and http://www.schema.net.