XML DTD

A “Well Formed” XML document is the one with correct syntax, while an XML document validated against a DTD is both “Well Formed” and “Valid”.

What is DTD?

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

Valid XML Documents:

Along with being “Well Formed”, a “Valid” XML document conforms to the rules of a DTD.

Example:

<?xml version="1.0" encoding="UTF-8"?>
<!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>

Explanation:

In the above example, the DOCTYPE declaration contains a reference to a DTD file whose content is discussed below.

XML DTD:

To define the structure and the legal elements and attributes of an XML document, a DTD comes into existence.

Note.dtd:

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

Explanation:

Here, the #PCDATA means parseable character data.

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”

Using DTD for Entity Declaration:

To define special characters or strings used in a document, a DOCTYPE declaration can be used. An entity has three parts. These are:

  • starts with an ampersand (&)
  • then the entity name
  • ends with a semicolon (;)

Example:

<?xml version="1.0" encoding="UTF-8"?>
 
<!DOCTYPE note [
<!ENTITY nbsp "&#xA0;">
<!ENTITY writer "Writer: Me.">
<!ENTITY copyright "Copyright: Mine.">
]>
 
<note>
<to>Sapna</to>
<from>Tom</from>
<heading>Meeting</heading>
<body>Meeting on Monday Morning at 9 AM.</body>
<footer>&writer;&nbsp;&copyright;</footer>
</note>

When to Use a DTD?

Independent groups of people can agree to use a standard DTD for interchanging data. We can verify that the data received from the outside world is valid and we can also verify our data.

When NOT to Use a DTD?

There is no requirement of a DTD in XML, especially while experimenting with XML, or working with small XML files, creating DTDs may be a waste of time. Before adding a DTD while developing an application, we should wait until the specification is stable. Or else the validation errors might stop the application from working.

Please Share