How to Bind XML to XSD with xsi:schemaLocation
This article explains how to associate an XML instance document with
an XML Schema Definition (XSD) using the xsi:schemaLocation
attribute. It covers the required XML Schema Instance namespace
declaration, the two-part value structure of the attribute, a complete
code example, and how XML processors interpret this instruction to
validate document structure.
The Role of xsi:schemaLocation
The xsi:schemaLocation attribute provides a hint to an
XML parser regarding the physical location of an XSD file used to
validate elements within a specific namespace. It allows validating
parsers to automatically locate, download, or read the schema file
associated with the document’s content.
Step 1: Declare the XMLSchema-instance Namespace
Before using xsi:schemaLocation, the XML document must
declare the standard W3C XML Schema Instance namespace. This is
typically done on the root element using the xmlns:xsi
attribute:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"Step 2: Structure the xsi:schemaLocation Value
The value of xsi:schemaLocation consists of
whitespace-separated pairs of URIs. Each pair contains two components in
exact order:
- Target Namespace: The namespace URI declared in the
target XSD (
targetNamespace). - Schema Location: The URI, relative file path, or
absolute URL where the
.xsdfile is located.
Multiple namespace-to-schema pairs can be defined within the same attribute, separated by spaces or line breaks:
xsi:schemaLocation="[Namespace_URI_1] [Schema_Location_1] [Namespace_URI_2] [Schema_Location_2]"
Complete XML Example
Below is a complete XML document binding the default namespace
https://www.example.com/orders to a local schema file named
orders.xsd:
<?xml version="1.0" encoding="UTF-8"?>
<order xmlns="https://www.example.com/orders"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.example.com/orders orders.xsd">
<orderId>12345</orderId>
<customerName>Jane Doe</customerName>
<item>
<productId>A987</productId>
<quantity>2</quantity>
<price>19.99</price>
</item>
</order>How the Parser Processes the Binding
When a schema-aware parser encounters this XML:
- It identifies
xsi:schemaLocationvia thehttp://www.w3.org/2001/XMLSchema-instancenamespace. - It splits the attribute’s value into namespace and location pairs.
- It fetches the schema from
orders.xsdand verifies that itstargetNamespacematcheshttps://www.example.com/orders. - It validates the XML elements against the rules, data types, and structures defined in the fetched schema.
Handling Documents Without Namespaces
If an XML document does not use namespaces,
xsi:schemaLocation cannot be used. Instead, use the
xsi:noNamespaceSchemaLocation attribute, which takes a
single value indicating the direct path to the schema file:
<order xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="orders.xsd">
<orderId>12345</orderId>
</order>