HomeXML Page 6 - Doing More With XML Schemas (part 4)
Being Selective - XML
In this concluding article, find out all about namespaces - what they are, how they work, and how you can use schemas to make sure that they're enforced in a consistent manner.
The previous examples have demonstrated how a schema designer can force a document author to qualify an XML document with appropriate namespaces. However, based on what we've seen thus far, this is an all-or-nothing proposition - either every element is qualified or every element is unqualified - which is not very practical for real-world use.
Fortunately, the XML Schema specification also provides a "form" attribute for each element and attribute definition, which allows you to specify qualification rules on a case-by-case basis. Consider the following example, which demonstrates:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="http://www.somedomain.com/ns/sw/"
xmlns:sw="http://www.somedomain.com/ns/sw/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!--
define a complex type -->
<xsd:complexType name="starWarsEntity">
<xsd:sequence>
<xsd:element
name="name" type="xsd:string"
form="qualified"/>
<xsd:element name="species"
type="xsd:string"
form="unqualified"/>
<xsd:element name="language" type="xsd:string"
form="unqualified"/>
<xsd:element
name="home" type="xsd:string"
form="qualified"/>
</xsd:sequence>
</xsd:complexType>
<!--
define the root element and its contents -->
<xsd:element name="gallery">
<xsd:complexType>
<xsd:sequence>
<xsd:element
name="character"
type="sw:starWarsEntity" maxOccurs="unbounded" form="qualified"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
As you can see, I've introduced the "form" attribute into the element definitions
above. Like its schema-level cousins, this attribute too takes two values: "qualified" and "unqualified". In the example above, the <character>, <name> and <home> elements are all to be qualified with namespaces; the others may remain unqualified.
And here's an XML document instance conforming to the schema above: