Target Namespaces

Contact Us or call 1-877-932-8228
Target Namespaces

Target Namespaces

A schema can be used to populate a namespace. So far, we have not created namespaces with our schemas. That is why the root elements of our XML instances all include the xsi:noNamespaceSchemaLocation attribute.

To populate a namespace with an XML schema, set the targetNamespace attribute of the xs:schema element to a URI. You must also include a xmlns attribute, so that global elements declared in the target namespace can be referenced within the schema.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://webucator.com/Artist" xmlns="http://webucator.com/Artist">

Code Sample:

Namespaces/Demos/Artist.xsd
<?xml version="1.0"?>
<xs:schema targetNamespace="http://www.webucator.com/Artist" 
	xmlns:xs="http://www.w3.org/2001/XMLSchema" 
	xmlns="http://www.webucator.com/Artist">
	<xs:element name="Title" type="xs:string"/>
	<xs:element name="FirstName" type="xs:string"/>
	<xs:element name="LastName" type="xs:string"/>
	<xs:element name="Name">
		<xs:complexType>
			<xs:sequence>
				<xs:element ref="Title"/>
				<xs:element ref="FirstName"/>
				<xs:element ref="LastName"/>
			</xs:sequence>
		</xs:complexType>
	</xs:element>
	<xs:element name="Artist">
		<xs:complexType>
			<xs:sequence>
				<xs:element ref="Name"/>
			</xs:sequence>
			<xs:attribute name="BirthYear" type="xs:gYear" use="required"/>
		</xs:complexType>
	</xs:element>
</xs:schema>

This schema would be invalid if the xmlns="http://www.webucator.com/Artist" attribute were removed. That's because the Name and Artist element declarations have child elements that reference elements declared in this schema. We can only reference elements that are declared globally in namespaces used in the document (as indicated by the xmlns attributes).

Instance documents of this XML schema would take the xmlns and xsi:schemaLocation attributes. Again, the xmlns attribute allows global elements declared in the specified namespace to be used in this instance. The xsi:schemaLocation attribute is used to point to the schema associated with a namespace. Its value is the namespace name and the path to the schema separated by a space.

Code Sample:

Namespaces/Demos/MichaelJackson.xml
<?xml version="1.0"?>
<Artist BirthYear="1958" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.webucator.com/Artist"
	xsi:schemaLocation="http://www.webucator.com/Artist Artist.xsd">
	<Name>
		<Title>Mr.</Title>
		<FirstName>Michael</FirstName>
		<LastName>Jackson</LastName>
	</Name>
</Artist>
Next