Doing More With XML Schemas (part 3) - Taking On The Fleet
(Page 4 of 6 )
Let's look at another example to better understand how keys and references work. This time, I'll leave the all-too-human world of supermarkets and travel back to that galaxy far, far away, to see exactly what's sitting in the cargo hold of two of the better-known starships in the Star Wars fleet.
<?xml version="1.0" encoding="UTF-8"?>
<fleet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ship
name="Jabitha">
<droid type="R2D2">2</droid>
<droid type="C3PO">4</droid>
</ship>
<ship
name="Millennium Falcon">
<droid type="R2D2">1</droid>
<droid type="C3PO">1</droid>
</ship>
</fleet>
Here's the schema against which this document would be validated.
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element
name="fleet">
<xsd:complexType>
<xsd:sequence>
<xsd:element
name="ship" type="shipType"
maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType
name="droidType">
<xsd:simpleContent>
<xsd:extension base="xsd:string">
<xsd:attribute
name="type"
type="xsd:string"/>
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
<xsd:complexType
name="shipType">
<xsd:sequence>
<xsd:element name="droid" type="droidType"
maxOccurs="unbounded"/>
</xsd:sequence>
<xsd:attribute
name="name" type="xsd:string"/>
</xsd:complexType>
</xsd:schema>
Now, let's suppose I wanted to add a couple more droids to the Falcon. Sure,
I could add another <ship> element with the same name...or I could do the smart thing, and add another <droid> element to the existing definition. As discussed in the previous example, the latter option is much cleaner, and also fairly easy to implement via the <xsd:unique> element. Here's the relevant snippet of the updated schema definition:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!-- snip -->
<xsd:element
name="fleet">
<xsd:complexType>
<xsd:sequence>
<xsd:element
name="ship" type="shipType"
maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:unique
name="NoRedefines">
<xsd:selector xpath="ship"/>
<xsd:field xpath="@name"/>
</xsd:unique>
</xsd:element>
<!--
snip -->
</xsd:schema>
In order to verify this, you can try creating two <ship> elements with the
same "name", and seeing your XML validator throw up all over the screen. It's always fun to watch, and it doesn't hurt anything!
Next: Breaking The Mold >>
More XML Articles
More By Harish Kamath, (c) Melonfire