- The Utility of Namespaces
- The Schema Namespace
- Target Namespaces
- The XML Schema Instance Namespace
- Namespace Issues with Multipart Schemas
The XML Schema Instance Namespace
Because DTDs were around when XML was developed, an easy mechanism exists (the DOCTYPE declaration) for including a DTD with an XML instance document. However, no such mechanism existed for associating an XML Schema. This gave rise to a special namespace, called the XML Schema Instance Namespace, which is used to associate XML Schemas with instance documents. For example, let's say we have the following pencil.xsd schema:
<?xml version="1.0" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="pencil"> <xs:element name="color"/> <xs:element name="type"/> <xs:element name="size"/> </xs:element> </xs:schema>
Now, if we want to include this in an XML instance document, we need to use the XML Schema Instance Namespace, which generally has an XSI prefix. We can do that with an xmlns attribute:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
With the xsi namespace defined, we can now make used of a special attribute called schemaLocation. This attribute accepts two values. The first is the namespace of the XML Schema to which we're pointing, and the second is the location of the XML Schema itself:
xsi:schemaLocation="http://www.mycompany.com/Pencil http://www.mycompany.com/pencil.xsd"
The two values are contained in quotes and only separated by a space. If we bring all the declarations together in an XML instance document, the result is as follows:
<?xml version="1.0" ?> <pencil xmlns="http://www.mycompany.com/Pencil" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mycompany.com/Pencil http://www.mycompany.com/pencil.xsd"> <color>Black (Graphite)</color> <type>Wood</type> <size>No. 2</size> </pencil>
While the root pencil element is now a bit difficult to read, we have a namespace defined for the whole document (http://www.mycompany.com/Pencil) and we have the xsi namespace defined, which allows us to use the schemaLocation attribute to point to the location of the schema for our document.