An Introduction to RELAX NG - Adding child elements
(Page 3 of 4 )
Of course, if we're to follow the scenario of a list of people mentioned earlier, then the people element will need to contain person elements, not text. In order to make room for a child element in the schema, we simply need to place one element within the parent. So, in the XML schema, the text element needs to be replaced with another element element. Just as before, this element also needs to have some sort of child. For now, we'll just make it empty:
<element name="people" xmlns="http://relaxng.org/ns/structure/1.0">
<element name="person">
<empty/>
</element>
</element>
The process for the compact schema is very simple. The child element simply needs to be placed within the parent element:
element people {
element person { empty }
}
Now, in the instance document, we're able to place a person element within the people element:
<people>
<person/>
</people>
However, there's one problem: in the schema, we've provided for one element. If we're to create a list of people, though, we need to provide for multiple elements within the schema. This isn't very hard, but there are two ways we can do this. We can either allow one or more person elements, or we can allow zero or more person elements. So, the choice is really between allowing the people element to be empty or not. Let's start by allowing one or more person elements. In the XML schema, this is done by placing the element's definition within a oneOrMore element:
<element name="people" xmlns="http://relaxng.org/ns/structure/1.0">
<oneOrMore>
<element name="person">
<empty/>
</element>
</oneOrMore>
</element>
In the compact schema, the process is even simpler. The compact syntax uses quantifiers like the ones found in regular expressions. The quantifiers are placed after the element to be quantified. So, in order to specify that one or more of an element is to appear, an addition symbol (“+”) is added after the element's definition:
element people {
element person { empty }+
}
Multiple person elements can now appear in the document, as long as there is at least one:
<people>
<person/>
<person/>
</people>
The process for allowing zero or more elements to appear is very similar. For the XML schema, the zeroOrMore element is used:
<element name="people" xmlns="http://relaxng.org/ns/structure/1.0">
<zeroOrMore>
<element name="person">
<empty/>
</element>
</zeroOrMore>
</element>
And for the compact schema, an asterisk (“*”) is added after the element's definition:
element people {
element person { empty }*
}
Now the document will validate even if the people element is empty:
<people>
</people>
Next: Adding attributes >>
More XML Articles
More By Peyton McCullough