ID and IDREF in XML DTD: Referential Integrity

This article explains how the ID and IDREF attribute types function within an XML Document Type Definition (DTD) to establish relationships and maintain referential integrity. It explores the syntax of these attributes, the validation rules enforced by XML parsers, practical implementation examples, and the inherent limitations of DTD-based validation compared to modern schema languages.

Understanding ID and IDREF

In an XML DTD, ID and IDREF are specialized attribute types used to establish internal links between different elements within the same XML document, functioning similarly to primary and foreign keys in a relational database.

How Referential Integrity is Enforced

When an XML parser validates a document against its DTD, it enforces referential integrity through two primary constraints:

1. The Uniqueness Constraint (ID)

A validating XML parser ensures that every ID value is unique across the entire XML document. If two elements share the same ID value—regardless of whether they are the same element type or completely different elements—the parser reports a validation error.

Additionally, ID values must adhere to XML Name syntax: * They must begin with a letter or an underscore (_). * They cannot begin with a number or contain spaces. * An element can have at most one attribute of type ID.

2. The Existence Constraint (IDREF)

The validating parser verifies that every value assigned to an IDREF attribute matches an existing ID value in the document. If an IDREF points to a value that does not exist on any ID attribute, the parser throws a validation error. This prevents broken links and orphaned references, guaranteeing that referenced data is always present.

DTD Declaration and XML Example

DTD Declaration

In the DTD, attributes are declared using the ATTLIST declaration:

<!ELEMENT library (authors, books)>
<!ELEMENT authors (author+)>
<!ELEMENT author EMPTY>
<!ATTLIST author
    id ID #REQUIRED
    name CDATA #REQUIRED>

<!ELEMENT books (book+)>
<!ELEMENT book EMPTY>
<!ATTLIST book
    isbn CDATA #REQUIRED
    title CDATA #REQUIRED
    authorRef IDREF #REQUIRED>

Valid XML Document

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE library SYSTEM "library.dtd">
<library>
    <authors>
        <author id="auth_01" name="Jane Doe"/>
        <author id="auth_02" name="John Smith"/>
    </authors>
    <books>
        <book isbn="978-1234567890" title="XML Basics" authorRef="auth_01"/>
        <book isbn="978-0987654321" title="Advanced DTD" authorRef="auth_02"/>
    </books>
</library>

In this example, if authorRef were set to "auth_99" (a non-existent ID), the validating parser would reject the document due to a broken reference.

Limitations of DTD Referential Integrity

While ID and IDREF provide baseline referential integrity, they possess significant architectural constraints: