How to Use XML DTD Occurrence Operators
In an XML Document Type Definition (DTD), child element occurrence
operators dictate how many times a specific child element can appear
within its parent element. By default, an element declared inside a
parent must appear exactly once. To modify this strict frequency rule,
DTD provides three primary occurrence indicators: the question mark
(?), the asterisk (*), and the plus sign
(+). Understanding how to apply these operators allows you
to create flexible, valid schema definitions for structured data.
The Default Behavior (No Operator)
When a child element is listed inside an
<!ELEMENT> declaration without any occurrence symbol,
it is mandatory and can appear only once.
<!ELEMENT book (title, author)>In this example, every <book> element must contain
exactly one <title> followed by exactly one
<author>.
The Question Mark
(?): Zero or One Time
The question mark indicates that an element is optional. It can appear either zero times or exactly one time.
<!ELEMENT person (name, nickname?)>- Usage: Place
?immediately after the element name. - Result: A
<person>element must have a<name>and may optionally include a single<nickname>. Including more than one<nickname>or omitting<name>will cause a validation error.
The Asterisk (*):
Zero or More Times
The asterisk allows an element to appear any number of times, including not at all. It represents an optional, repeatable element.
<!ELEMENT library (book*)>- Usage: Place
*immediately after the element name. - Result: The
<library>element can contain no<book>elements, one<book>, or hundreds of<book>elements.
The Plus Sign (+):
One or More Times
The plus sign requires the element to appear at least once, but it also allows the element to repeat indefinitely.
<!ELEMENT chapter (title, paragraph+)>- Usage: Place
+immediately after the element name. - Result: A
<chapter>must have one<title>and must have at least one<paragraph>. It can contain multiple<paragraph>elements, but omitting the<paragraph>entirely will result in a validation error.
Using Operators with Groups and Choices
Occurrence operators can also be applied to grouped element lists using parentheses to control sequences or choices.
<!ELEMENT document (header, (section | note)+, footer?)>header: Exactly once.(section | note)+: The document must contain at least one element that is either a<section>or a<note>, and these can repeat in any combination.footer?: An optional single<footer> element.