Introduction to DTDs

Creating Attributes

In the previous unit we learned the basic syntax of the DTD language to define a set of rules for our XML documents. We saw how rules for element names and element content can be defined. Now we will have a look at how attributes and attribute values can be defined in DTDs.

In the last unit we built a DTD for the following address book XML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<addressBook>
    <entry>
         <name>Clark Kent</name>
         <address>344 Clinton Street Metropolis</address>
         <phoneNr>55 50145</phoneNr>        
        <relationship/>
  </entry>
  <entry>
          <name>Bruce Wayne</name>
          <address>1007 Mountain Drive Gotham</address>
          <phoneNr>53 59333</phoneNr>  
          <relationship/>
   </entry>
</addressBook>


The element ‘relationship’ is an empty element containing no data and is therefore not meaningful yet. We will learn now how to add a ‘type’ attribute that contains information about the type of relationship. The DTD code that defines the above XML is the following:




1
2
3
4
5
6
7
<!DOCTYPE addressBook [
            <!ELEMENT addressBook (entry*)>
            <!ELEMENT entry (name, address, phoneNr, relationship)>
            <!ELEMENT name (#PCDATA)>
            <!ELEMENT address (#PCDATA)>
            <!ELEMENT phoneNr (#PCDATA)>
            <!ELEMENT relationship EMPTY> ]>


The following DTD statement defines an attribute named ‘type’ for the element ‘relationship’.

1
<!ATTLIST relationship type CDATA #REQUIRED>

The components of this statement are:

<!

Start of attribute definition

ATTLIST

declares an attribute list

relationship

declares the element to which the attribute belongs

type

declares the attribute name

CDATA

defines the content type of the attribute, CDATA stands for ‘character data’

#REQUIRED

declares that this attribute is mandatory on every ‘relationship’ element

> 

End of attribute definition

 

DTDs allow to specify different content types for attributes. Besides character data (CDATA) the values … are possible.

For some attributes it is useful to specify predefined values. This can be done by adding the predefined values in round brackets after the attribute name instead of the CDATA in the example above:

1
<!ATTLIST relationship type (private|work) #REQUIRED>

 

One attribute list can contain several attributes of an element. For instance, the following statements declares the attributes ‘first’, ‘second’ and ‘title’ on the name element:

1
2
<!ATTLIST name first CDATA #REQUIRED second CDATA #REQUIRED
title CDATA #REQUIRED>


 All attributes that we defined here are mandatory as indicated by the #REQUIRED statement. In order to make an attribute optional #REQUIRED has to be replaced with #IMPLIED. As in the example of the ‘title’ attribute here:

<!ATTLIST name first CDATA #REQUIRED second CDATA #REQUIRED 
title CDATA #IMPLIED>