A Document Type Definition (DTD) is a set of rules that defines the elements, element attribute and attribute values, and the relationship between elements in a document.
When your XML document is processed, it is compared to its associated DTD to be sure it is structured correctly and all tags are used in the proper manner. This comparison process is called validation and is is performed by a tool called a parser.
Remember, you don't need to have a DTD to create an XML document; you only need a DTD for a valid XML document.
Here's a few reasons you'd want to use a DTD:
- Your document is part of a larger document set and you want to ensure that the whole set follows the same rules.
- Your document must contain a specific set of data and you want to ensure that all required data has been included.
- Your document is used across your industry and need to match other industry-specific documents.
- You want to be able to error check your document for accuracy of tag use.
Deciding on a DTD
Using a DTD doesn't necessarily mean you have to create one from scratch. There are a number of existing DTDs, with more being added everyday
As XML becomes wide-spread, your industry association or company is likely to have one or more published DTDs that you can use and link to. These DTDs define tags for elements that are commonly used in your applications. You don't need to recreate these DTDs -- you just point to them in your doctype tag in your XML file, and follow their rules when you create your XML document.
Some of these DTDs may be public DTDs, like the HTML DTD. Others may belong to your company. If you are interested in using a DTD, ask around and see if there is a good match that already exists.
Create Your Own DTD
Another option is to create your own DTD. The DTD can be very simple and basic or it can be large and complex. The DTD will be a reflection of the needs of your document.
It is perfectly acceptable to have a DTD with just four or five basic elements if that is what your document needs. Don't feel that creating a DTD necessarily needs to be a huge undertaking.
However, if your documents are complex, do plan on setting aside timeseveral days or several weeks -- to understand the document and the document elements and create a solid DTD that will really work for you over time.
Make an Internal DTDs
You can insert DTD data within your DOCTYPE definition. If you're worked with CSS styles, you can think of this as being a little like putting style data into your file header. DTDs inserted this way are used in that specific XML document. This might be the approach to take if you want to validate the use of a small number of tags in a single document or to make elements that will be used only for one document.
Remember, the primary use for a DTD is to validate that the tags you enter in your XML document are entered as specified in the DTD. It is an error-checking process that ensures your data conforms to a set a rules.