DTD Tutorial

What is DTD?

DTD or Document Type Definition is used to define the structure and the legal elements and attributes of an XML document.

Why Use a DTD?

Independent groups of people can agree to use a standard DTD for interchanging data. An application can also verify that the XML data is valid.

An Internal DTD Declaration:

The DTD must be wrapped inside the <!DOCTYPE> definition, in case it is declared inside the XML file.

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>Sapna</to>
<from>Tom</from>
<heading>Meeting</heading>
<body>Meeting on Monday Morning at 9 AM.</body>
</note>

Explanation:

To view the DTD, we can select “view source”, in the XML file. Interpretation of the above DTD:

  • !DOCTYPE note – Used to define that note is the root element of the document.
  • !ELEMENT note – Used to define that the note element must contain the elements: “to, from, heading, body”.
  • !ELEMENT to – Used to define that the “to” element is to be of type “#PCDATA”.
  • !ELEMENT from – Used to define that the “from” element is to be of type “#PCDATA”.
  • !ELEMENT heading – Used to define the heading element to be of type “#PCDATA”.
  • !ELEMENT body – Used to define the body element to be of type “#PCDATA”

An External DTD Declaration:

A reference to the DTD file should be included in the <!DOCTYPE> definition, if the DTD is declared in an external file.

XML document with a reference to an external DTD:

<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
 <to>Sapna</to>
<from>Tom</from>
<heading>Meeting</heading>
<body>Meeting on Monday Morning at 9 AM.</body>
</note>

Note.dtd:

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

DTD Tutorial List

Content Protection by DMCA.com