Datatypes and More in RELAX NG - Creating named patterns
(Page 3 of 4 )
Even though there has been no difference in how the document validates, the explicit creation of the grammar element allows named patterns to be created in order to better organize the document. If you examine the schema, the hierarchy of it gets a bit complex. In the XML schema, some elements are indented quite a bit. While our schema is not very complex in function, it's easy to see how a more complex schema can get real messy.
Named patterns simply allow us to break up the schema into more manageable chunks. Validation won't be affected, only the appearance and manageability of the schema. Using named patterns, a chunk of the schema can be removed from the rest, given a name, and then referenced by name where needed. This will create manageable chunks rather than one giant hierarchy of elements.
To create a named pattern using the XML syntax, the define element is used. The define element must be a child of the grammar element. The pattern is named using the name attribute, and inside of the element is the actual pattern.
The section of the schema dealing with location is probably the most complex part. So, let's turn it into a named pattern. This can be done by simply cutting and pasting the pattern inside of a define element. We'll call the new pattern “location.” Here's what the new element looks like:
<define name="location">
<choice>
<element name="zipCode">
<text/>
</element>
<group>
<element name="city">
<text/>
</element>
<element name="state">
<text/>
</element>
</group>
</choice>
</define>
Remember, the define element must be a child of the grammar element.
Now the pattern needs to be referenced where it appears in the schema. The ref element is used to accomplish this. Its name attribute must be set to the name of the pattern that's being referenced. So, in the spot formerly occupied by the XML just removed from the schema, the following element is placed:
<ref name="location"/>
Next: Creating named patterns, continued >>
More XML Articles
More By Peyton McCullough