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:




Sapna
Tom
Meeting
Meeting on Monday Morning at 9 AM.

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:






]>

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:






]>


Sapna
Tom
Meeting
Meeting on Monday Morning at 9 AM.
&writer; ©right;

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.