HomeXML Page 3 - Doing More With XML Schemas (part 4)
The Name Game - 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.
Setting up a namespace is simple - here's the syntax:
<elementName xmlns:prefix="namespaceURL">
In this case, the prefix is the unique string used to identify the namespace; this is linked to a specific namespace URL.
A namespace is usually declared at the root element level, although authors are free to declare it at a lower level of the tree structure too.
Once the namespace has been declared within the document, it can be used by prefixing each element within that namespace with the unique namespace identifier. Take a look at my revised stock portfolio, which now uses a "mytrades" namespace to avoid name clashes.
In case you're wondering, the namespace URL is simply a pointer to a Web address, and is meaningless in practical terms; the XML specification doesn't really care where the URL points, or even if it's a valid link.{mospagebreak title=All About Character} Here's an XML document instance which uses namespaces to qualify each element,
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.somedomain.com/ns/sw/"
xmlns:sw="http://www.somedomain.com/ns/sw/"
elementFormDefault="qualified">
<!--
define a complex type -->
<xsd:complexType name="starWarsEntity">
<xsd:sequence>
<xsd:element
name="name" type="xsd:string"/>
<xsd:element name="species" type="xsd:string"/>
<xsd:element
name="language" type="xsd:string"/>
<xsd:element name="home" type="xsd:string"/>
</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"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
The most important line of code in this entire schema is the first line, which
defines the namespace used to identify the elements and attributes in the XML document instance.
The "targetNamespace" attribute specifies the namespace for this schema, and
is what the XML parser/validator uses to differentiate between a <character> in the Star Wars universe, and a <character> from any other source. Note that the namespace URL in the schema matches the namespace URL in the document instance above.
Within the XML document instance itself, the "sw" namespace is defined at the top of the document as usual, together with a URL that specifies the location of the schema to be used for validation of that namespace (note that this URL is specified via the "schemaLocation" attribute).