Monday, May 30, 2011

Limit number of element occurrences with DTD

Both DTD and XML Schema allow the restriction of how many times an element occurs. DTD has modifiers that allow the limiting of element occurrences: * ? and +. If you add any of these symbols to an element, the amount of times it can occur is restricted.

<!ELEMENT Computer (Disk?)> means the Disk element can occur zero or once.
<!ELEMENT Computer (Disk+)> means the Disk element can occur one or more times.
<!ELEMENT Computer (Disk*)> means the Disk element can occur zero or more times.

XML Schema allows you to achieve the same result with minOccurs and maxOccurs attributes. In the following example, the Disk element can occur a minimum of once and a maximum of three times.


<xs:element name="Disk" type="xs:string" minOccurs="1" maxOccurs="3"/>


Can we perform the same restriction in DTD? It's messy, but possible! Use the OR operator (|) to specify a choice between the amount of options.

<!ELEMENT DiskSection (Disk | (Disk,Disk) | (Disk,Disk,Disk))>

Of course, anything more than a few options and it becomes very messy!

No comments:

Post a Comment