DTD - Sequences and Choices – Using , and | Operators

1. Introduction

When defining XML document structures in a DTD, we often need to specify how elements should appear inside a parent element. Two fundamental operators help control order and alternatives:

  • , (comma) → defines a sequence (order matters).

  • | (pipe) → defines a choice (one of several options).

These operators allow you to model flexible but controlled content models.


2. Sequences with ,

A sequence enforces that elements must appear in a specific order.

Syntax:

<!ELEMENT parent (child1, child2, child3)>

Example:

<!ELEMENT address (street, city, country)>

This means:

  • Every <address> must contain a <street>, followed by a <city>, followed by a <country>.

  • Order is mandatory: <city> before <street> would be invalid.

Valid XML:

<address>
  <street>Main Road</street>
  <city>Boston</city>
  <country>USA</country>
</address>

Invalid XML (wrong order):

<address>
  <country>USA</country>
  <city>Boston</city>
  <street>Main Road</street>
</address>

3. Choices with |

A choice specifies alternatives: one element OR another.

Syntax:

<!ELEMENT parent (option1 | option2 | option3)>

Example:

<!ELEMENT contact (email | phone)>

This means:

  • A <contact> must contain either <email> or <phone>, but not both at the same time.

Valid XML:

<contact>
  <email>[email protected]</email>
</contact>

or

<contact>
  <phone>123-456-7890</phone>
</contact>

Invalid XML (both included):

<contact>
  <email>[email protected]</email>
  <phone>123-456-7890</phone>
</contact>

4. Combining Sequences and Choices

Sequences and choices can be combined for more complex models.

Example:

<!ELEMENT person (name, (email | phone))>

This means:

  • Every <person> must have a <name> first.

  • After <name>, the person must provide either <email> or <phone>.

Valid XML:

<person>
  <name>Alice</name>
  <email>[email protected]</email>
</person>

Invalid XML (missing choice):

<person>
  <name>Alice</name>
</person>

5. Nesting and Grouping

Parentheses allow grouping of sequences and choices.

Example:

<!ELEMENT order ((creditCard | paypal), shippingAddress)>

This means:

  • <order> must include one payment option (creditCard or paypal)

  • Followed by a <shippingAddress>.


6. Best Practices

  • Use , when order matters (e.g., address, date).

  • Use | when order does not matter but alternatives are required.

  • Always group with parentheses when combining multiple operators.

  • Keep content models clear to avoid confusion in validation.


7. Conclusion

The , (sequence) and | (choice) operators are fundamental tools in DTDs for defining valid document structures. Sequences enforce strict order, while choices introduce flexibility by allowing alternatives. Together, they form the foundation for building structured, rule-driven XML models.