HomeXML Page 2 - Doing More With XML Schemas (part 3)
A Day At The Supermarket - XML
This article introduces you to the concept of uniqueness in the XML Schema world, showing you how to use built-in schema constructs to enforce uniqueness within your XML document instances.
What's a supermarket got to with an XML schema, you ask wonderingly? Quite a lot, actually. You see, all supermarkets consist of aisles, with products placed neatly in each aisle for customers and employees alike. In an XML document, this design would be represented as follows:
As you can see, I have a list of <aisle> elements, which in turn enclose multiple
<item> elements. Each <aisle> is associated with a "name" that represents the category of items in the aisle, and a "number", which is used for easy reference. Each <item> is associated with a "quantity" and a "price".
Writing an XML schema to validate the XML document instance above is child's play, especially considering the amount of practice I've had over the last couple of weeks.
Now, let's suppose that, one fine day, the store manager decides to add a few
items to aisle 1. In the XML universe, he has two options available to him: he could add it to the existing <item> list for the appropriate aisle, or he could add another <aisle> element to the bottom of the document instance, reference it with the same aisle number, and attach the new items there.
With option two, the XML document instance doesn't look as clean as it did initially.
Proceeding along this path, it would soon have a number of different entries for the same <aisle> at different locations in the document tree. Obviously, this is a maintenance nightmare.
You can prevent this from happening via the very cool <xsd:unique> element - as in the revised schema below:
The <xsd:unique> element is what gets the ball rolling - it is used to impose
uniqueness constraints on an XML document instance. You can assign it a name - I've called mine "NoRepeatAisle" - to makes its function clearer.
The <xsd:unique> element encloses <xsd:selector> and <xsd:field> elements, which help to identify the unique components of the document. The "xpath" attribute of the <xsd:selector> element contains an XPath expression that helps to limit the scope within which the uniqueness constraint will be applied. In my case, this is restricted to all the <aisle> elements that are the children of the <supermarket> element only; if there exist any other <aisle> elements in the hierarchy, this constraint is not valid.
The second element component of the uniqueness constraint is the <xsd:field> element, which specifies which attribute values should be unique - in the example above, this is the value of the "number" attribute.