A document type definition (DTD) defines the structure of a class of XML documents, making it possible to distinguish between classes. A DTD is a list of element and attribute definitions unique to a class. Once you have set up a DTD, you can reference that DTD in another document, or embed it in the current XML document.
The DTD for XML Order documents, discussed in “A sample XML document” looks like this:
<!ELEMENT Order (Date, CustomerId, CustomerName,Item+)> <!ELEMENT Date (#PCDATA)> <!ELEMENT CustomerId (#PCDATA)> <!ELEMENT CustomerName (#PCDATA)> <!ELEMENT Item (ItemId, ItemName, Quantity)> <!ELEMENT ItemId (#PCDATA)> <!ELEMENT ItemName (#PCDATA)> <!ELEMENT Quantity (#PCDATA)> <!ATTLIST Quantity units CDATA #IMPLIED>
Read line by line, this DTD specifies that:
An order must consist of a date, a customer ID, a customer name, and one or more items. The plus sign, “+”, indicates one or more items. Items signaled by a plus sign are required. A question mark in the same place indicates an optional element. An asterisk in the element indicates that an element can occur zero or more times. (For example, if the word“Item*” in the first line above were starred, there could be no items in the order, or any number of items.)
Elements defined by “(#PCDATA)” are character text.
The “<ATTLIST…>” definition in the last line specifies that quantity elements have a “units” attribute; “#IMPLIED”, at the end of the last line, indicates that the “units” attribute is optional.
The character text of XML documents is not constrained. For example, there is no way to specify that the text of a quantity element should be numeric, and thus the following display of data would be valid:
<Quantity unit=”Baker’s dozen”>three</Quantity>
<Quantity unit=”six packs”>plenty</Quantity>
Restrictions on the text of elements must be handled by the applications that process XML data.
An XML’s DTD must follow the <?xml version="1.0"?> instruction. You can either include the DTD within your XML document, or you can reference an external DTD.
To reference a DTD externally, use something similar to:
<?xml version="1.0"?> <!DOCTYPE Order SYSTEM "Order.dtd”> <Order> … </Order>
Here’s how an embedded DTD might look:
<?xml version="1.0"?> <!DOCTYPE Order [ <!ELEMENT Order (Date, CustomerId, CustomerName, Item+)> <!ELEMENT Date (#PCDATA) <!ELEMENT CustomerId (#PCDATA)> <!ELEMENT CustomerName (#PCDATA)> <!ELEMENT Item (ItemId, ItemName, Quantity)> <!ELEMENT ItemId (#PCDATA)> <!ELEMENT ItemName (#PCDATA)> <!ELEMENT Quantity (#PCDATA)> <!ATTLIST Quantity units CDATA #IMPLIED>
]> <Order> <Date>1999/07/04</Date> <CustomerId>123</CustomerId> <CustomerName>Acme Alpha</CustomerName>
<Item> … </Item> </Order>
DTDs are not required for XML documents. However, a valid XML document has a DTD and conforms to that DTD.