XML and DTDs
When reading articles and books about CSS and XHTML, we invariably encounter this maxim: id attribute values must be unique, but class attributes can be reused. Having laid some groundwork for getting ZwiftBooks ready for dynamic web content based on XML data, let’s dig a bit deeper into DTDs to see what makes XHTML and CSS work so well together, and how the rules about unique attributes is enforced. This will take us a little further along our path to XML mastery.
Our discussion of SVG introduced the DTD as a way to define the structure of an XML document and as a place to define shortcuts or entities for substitution. With a DTD, independent groups know what to expect when exchanging data. Also, your application can use a DTD to verify that the data you receive from the outside world is valid.
When defining XML vocabularies by using a DTD, it turns out that our ability to specify attribute content is much richer than what we can say about elements. For elements, we can say either that the element can contain text, as in this example:
<!ELEMENT author #PCDATA>
or that an element called book should contain subelements of author, title, and isbn:
<!ELEMENT book (author, title, isbn)>
But that’s about it for elements, as far as DTDs are concerned. However, for attributes we can do more. Not only can we say that an attribute called isbn should appear in a book element:
<!ATTRIBUTE book isbn #CDATA>
we can also set things up so that the value must be unique within the document:
<!ATTRIBUTE book isbn #ID>
If we include this specification in a ZwiftBooks DTD, the parser will check that all ISBNs are unique. Applying this to our web example, this is how XHTML is defined so that id attributes associated with page structure are unique within a web page. Behind the scenes, the XHTML DTD declares the id attribute as #ID so that there can only be one of each id in the document!