Introduction to XML | Defining XML Structures with DTD | Specifying Element Occurrence Counts
DTD lets you specify how many times an element may appear. Without a symbol, an element must appear exactly once. For example, this model allows only one product:
<!ELEMENT inventory (product)>
To allow one or more products, append +:
<!ELEMENT inventory (product+)>
Occurrence symbols
| Symbol | Allowed occurrences |
|---|---|
+ |
One or more |
? |
Zero or one |
* |
Zero or more |
| None | Exactly one |
Write the symbol after an element model:
<!ELEMENT element-name (child1-symbol)>
<!ELEMENT element-name (child1-symbol, child2-symbol, ...)>
<!ELEMENT element-name (child1-symbol, child2-symbol, ...)symbol>
The following DTD allows one or more products, optional details, and zero or more colors:
<!DOCTYPE inventory[
<!ELEMENT inventory (product+)>
<!ELEMENT product (name, quantity, details?)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT quantity (#PCDATA)>
<!ELEMENT details (weight, color*)>
<!ELEMENT weight (#PCDATA)>
<!ELEMENT color (#PCDATA)>
]>
Remember that optional elements need ? or *. Without a symbol, the element must appear once.