XML DTD Attribute Types Tutorial 🎯

beginner
21 min

XML DTD Attribute Types Tutorial 🎯

Welcome to our comprehensive guide on XML DTD Attribute Types! This tutorial is designed for both beginners and intermediate learners, providing a detailed understanding of XML Document Type Definitions (DTD) attribute types. Let's dive in!

What are XML Attribute Types? 📝

Attribute types in XML DTD help define the type of data that an attribute can hold. This can ensure consistency and validity in your XML documents.

Basic Attribute Types 💡

CDATA

CDATA is used to define a section of text that should not be parsed or interpreted as XML. It's useful when you have data containing XML-reserved characters.

xml
<!ATTLIST element_name attribute_name CDATA "default_value">

ID, IDREF, and IDREFS

These types are used for unique identifiers. ID is for defining unique identifiers within a single XML document. IDREF and IDREFS are used to reference those unique identifiers from other elements.

xml
<!ATTLIST element_name attribute_name ID "default_value"> <!ATTLIST element_name attribute_name IDREF #IMPLIED> <!ATTLIST element_name attribute_name IDREFS #IMPLIED>

Enumerated Attribute Types 💡

Enumerated attribute types restrict the attribute value to a predefined set of options.

xml
<!ATTLIST element_name attribute_name (option1 | option2 | option3) "default_value">

Numeric Attribute Types 💡

NMTOKEN, NMTOKENS, and NMTOKEN#

These types allow only alphanumeric characters and the underscore _. NMTOKEN is for a single token, NMTOKENS for multiple tokens separated by whitespace, and NMTOKEN# for a token followed by a number.

xml
<!ATTLIST element_name attribute_name NMTOKEN "default_value"> <!ATTLIST element_name attribute_name NMTOKENS (token1 token2) "default_value"> <!ATTLIST element_name attribute_name NMTOKEN# "default_value">

Enumerated Numeric Attribute Types 💡

NMTOKEN, NMTOKENS, and NMTOKEN# with restricted values

xml
<!ATTLIST element_name attribute_name (value1 | value2 | value3) "default_value"> <!ATTLIST element_name attribute_name (value1 value2) "default_value"> <!ATTLIST element_name attribute_name NMTOKEN# "default_value">

Practical Example 💡

Let's create an XML document with attributes using some of the discussed types.

xml
<!DOCTYPE Books SYSTEM "Books.dtd"> <Books> <Book id="book1" category="Fiction"> <Title>The Great Gatsby</Title> <Author>F. Scott Fitzgerald</Author> </Book> <Book id="book2" category="Non-Fiction"> <Title>The Power of Now</Title> <Author>Eckhart Tolle</Author> </Book> </Books>

Here's the corresponding DTD:

xml
<!ELEMENT Books (Book+)> <!ELEMENT Book (Title, Author)> <!ATTLIST Book id ID #REQUIRED> <!ATTLIST Book category (Fiction | Non-Fiction) "Fiction">

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `CDATA` attribute type do in XML DTD?

Stay tuned for our next lesson on XML DTD Entity References! 🚀