The element's attributes

Defining an attribute in DTD is similar to what we have done for the elements.

Naturally, we define attributes for elements. So, after saying that what we are talking about is an attribute - using the keyword ATTLIST - we spacify the related attribute, than the name we want to give to this attribute, its type and considerations on its value.

Here is an example:

<!ELEMENT reference (#PCDATA)>
<!ATTLIST reference source CDATA #REQUIRED>

We defined source as an attribute for reference, specifying it is just a character string, and that it is mandatory.
Now, in a XML defined accordingly to a DTD including these lines, a reference should look like this:
<reference source="12">42</reference>
If the attribute is not mandatory, we call it #IMPLIED.

If an attribute is used as an identifier, we use the keyword ID, and we should ensure the value is defined accordingly to the XML naming rules.

Often it makes sense that an attribute could assume just a few values, we can enforce this requisite showing an enumerated list of the acceptable values:
<!ATTLIST contact kind (Friend | Business | Relative) #IMPLIED>
Being IMPLIED, the kind attribute could not be present, buf if it is, it should have one of the enlisted valued:
<contact kind="Relative">

We can set a default value, specifying it as a double-quote delimited string:
<!ATTLIST contact kind (Friend | Business | Relative) "Friend">

The #FIXED attribute are used to implements constant values.

It is possible to specify more than an attribute, both in the same ATTLIST tag:

<!ATTLIST contact kind (Friend | Business | Relative) "Friend"

Or putting any attribute in its own single tag. Just a matter of testing.

For more details I suggest you to read Beginning XML by David Hunter et al (Wrox).

No comments:

Post a Comment