The purpose of a Document Type Definition 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 DOCTYPE declaration
If the DTD is included in your XML source file, it should be wrapped in a
DOCTYPE definition with the following syntax:
<!DOCTYPE root-element [element-declarations]>
|
Example XML document with a DTD: (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 above is interpreted like this:
!DOCTYPE note (in line 2) defines that this is a document of the type note.
!ELEMENT note (in line 3) defines the note element as having
four elements: "to,from,heading,body".
!ELEMENT to (in line 4) defines the to element to be of the type
"#PCDATA".
!ELEMENT from (in line 5) defines the from element to be of the
type "#PCDATA"
and so on.....
External DOCTYPE declaration
If the DTD is external to your XML source file, it should be wrapped in a
DOCTYPE definition with the following syntax:
<!DOCTYPE root-element SYSTEM "filename">
|
This is the same XML document as above, but 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>
|
And this is a copy of the file "note.dtd" containing the DTD:
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
|
Why use a DTD?
With DTD, each of your XML files can carry a description of its own format with
it.
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 the data you receive from
the outside world is valid.
You can also use a DTD to verify your own data.
|