DTD - Attributes

Declaring Attributes with Types:

Attributes are declared using the declaration. You specify the element name, attribute name, and attribute type. Here's an example:


In this example, the book element is declared as empty. It has three attributes: title, author, and year. title and author are of type CDATA, which means they can contain any character data. year is of type NMTOKEN, which means it can contain a name token (a string with no spaces or special characters).

A Default Attribute Value:

You can specify a default value for an attribute using the #IMPLIED keyword. Here's an example:

 

In this example, both the author and year attributes have the default value set to #IMPLIED, which means they are optional. If no value is provided for these attributes, the default value will be assumed.

#REQUIRED:

To specify that an attribute is required, you use the #REQUIRED keyword. Here's an example:

 

In this example, the author attribute is required for the book element. It must have a value, and if it is not provided, the XML document will be considered invalid.

#FIXED:

To specify a fixed or constant value for an attribute, you use the #FIXED keyword. Here's an example:

 

In this example, the author attribute is fixed with a value of "J.K. Rowling". It means that the attribute must have this value and cannot be changed.

Enumerated Attribute Values:

You can restrict the values of an attribute to a predefined set of options using enumerated attribute values. Here's an example:

 

In this example, the genre attribute can have either the value "fiction" or "non-fiction". The format attribute can have the value "hardcover", "paperback", or "ebook". Any other value will be considered invalid.