DTD Tutorial


DTD

A Document Type Definition (DTD) defines the structure and the legal elements and attributes of an XML document.

A DTD can be declared inside an XML document or in an external file.


What You Should Already Know

Before you continue you should have a basic understanding of the following:

  • HTML
  • XML

If you want to study these subjects first, find the tutorials on our Home page.


Why Use a DTD?

With a DTD, independent groups of people can agree to use a standard 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.


Internal DTD Declaration

If the DTD is declared inside the XML file, it must be wrapped inside the <!DOCTYPE> definition:

XML document with an internal DTD

<?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>

View XML file »

In the XML file, select "view source" to view the 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 must contain four elements: "to,from,heading,body"
  • !ELEMENT to defines the to element to be of type "#PCDATA"
  • !ELEMENT from defines the from element to be of type "#PCDATA"
  • !ELEMENT heading defines the heading element to be of type "#PCDATA"
  • !ELEMENT body defines the body element to be of type "#PCDATA"

External DTD Declaration

If the DTD is declared in an external file, the <!DOCTYPE> definition must contain a reference to the DTD file:

XML document with a reference to an external DTD

<?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>

View XML file »

And here is the file "note.dtd", which contains the DTD:

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


SHARE THIS PAGE

COLOR PICKER

colorpicker





Search w3schools.com:

Translate w3schools.com: