Providing Options in RELAX NG - Enumerations with the value element
(Page 3 of 4 )
In some situations, it's not an element or an attribute that a user should choose from, but, instead, a value. For example, consider a gender element. Valid values for this element consist of “male” and “female.” It is possible to limit the value of the element to one of these two values. In the XML schema, this can be done using the choice element in conjunction with the value element. Since there are two possible values, we need two value elements, one for “male” and one for “female.” The two value elements will be children of the choice element. The resulting XML schema will look like this:
<element name="gender">
<choice>
<value>male</value>
<value>female</value>
</choice>
</element>
(If you're following along on your own, make sure to place this at the end of the person element's declaration. The order of elements matters in RELAX NG. We'll get to this in a moment).
The process is even simpler using the compact syntax. Just as before, the pipe character is used, only this time the choice is between two values and not between two elements. Here's what the new compact schema looks like:
element people {
element person {
attribute date { text }?,
(element zipCode { text }
| (element city { text },
element state { text })),
element gender { "male" | "female" }
}*
}
Now the following XML will validate because the values in the gender element are valid:
<people>
<person date="2008-06-30">
<city>Topeka</city>
<state>Kansas</state>
<gender>male</gender>
</person>
<person>
<zipCode>29555</zipCode>
<gender>female</gender>
</person>
</people>
However, if we were to specify a value other than “male” or “female,” then the document would not validate:
<person>
<zipCode>29555</zipCode>
<gender>unknown</gender>
</person>
The above modification would result in an invalid document.
Of course, this concept isn't restricted to elements. Attributes can also make use of this using the same process.
Next: Element order and interleaving >>
More XML Articles
More By Peyton McCullough