Pages

Wednesday, September 21, 2011

Restrict the number of elements in a document with XML XSD occurrence indicators

XML Schema Definition language provides mechanisms for specifying how many times each element may occur in a document. XSD accounts for all the same occurrence actions as DTDs, plus the ability to specify exact occurrence numbers or number ranges. For example, we’ll use a para element to illustrate the various methods for indicating occurrence in XSD:

1. <xs:element name="para"/glt;

This rule states that there must be one para element.

2. <xs:element name="para" minOccurs="0" maxOccurs="1"/glt;

This rule is the same as the "optional" indicator in XML DTDs. That is, you can have one para, but it’s optional.

3. <xs:element name="para" minOccurs="1" maxOccurs="unbounded"/glt;

This rule is the same as the DTD "one or more" indicator. You must have at least one para, but you can have as many as you want, hence the term "unbounded."

4. <xs:element name="para" minOccurs="0" maxOccurs="unbounded"/glt;

This rule is the same as the DTD "zero or more." You don’t have to have any paras, but you can have as many as you want.

5. <xs:element name="para" minOccurs="2"/glt;

This rule isn’t possible in DTDs. It says you must have two paras--no more, no less.

6. <xs:element name="para" minOccurs="2" maxOccurs="5"/glt;

This rule also isn’t possible in DTDs. It specifies a specific range; you must have at least two paras, but no more than five.

Basically, with the minOccurs and maxOccurs attributes, you can specify any number range you need for elements within your document or data set.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.