Difference Between xs:include and xs:import in XSD
When modularizing an XML Schema Definition (XSD),
xs:include and xs:import are the two primary
mechanisms used to combine multiple schema documents. The fundamental
difference between them lies in how they handle namespaces:
xs:include is used to merge schema documents that share the
same target namespace (or adopt the including schema’s namespace), while
xs:import is used to bring in schema components from a
completely different target namespace.
The Purpose of xs:include
The xs:include element allows you to split a single
large schema into smaller, manageable files within the same
target namespace.
Key characteristics of xs:include: * Same
Namespace: The included schema file must have the identical
targetNamespace as the parent schema, or it must not define
a targetNamespace at all. * Chameleon
Effect: If the included schema has no
targetNamespace, it automatically inherits and adopts the
targetNamespace of the including schema document. *
Attributes: It primarily uses the
schemaLocation attribute to specify the URI or file path of
the schema to be incorporated.
Example:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://example.com/ns/orders"
xmlns="http://example.com/ns/orders">
<xs:include schemaLocation="customer-types.xsd"/>
</xs:schema>The Purpose of xs:import
The xs:import element allows a schema to reference
elements, types, and attributes defined in a different target
namespace.
Key characteristics of xs:import: * Different
Namespaces: It is strictly used when integrating types across
distinct namespaces. * Prefix Binding: To use types
from the imported schema, you must declare an xmlns prefix
for that namespace at the top of your schema document. *
Attributes: It requires a namespace
attribute to identify the foreign namespace and typically uses an
optional schemaLocation attribute to locate the actual XSD
file.
Example:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://example.com/ns/orders"
xmlns:common="http://example.com/ns/common">
<xs:import namespace="http://example.com/ns/common"
schemaLocation="common-definitions.xsd"/>
<xs:element name="OrderDate" type="common:CustomDateType"/>
</xs:schema>Summary of Key Differences
| Feature | xs:include |
xs:import |
|---|---|---|
| Namespace Relationship | Same target namespace | Different target namespaces |
| Namespace Attribute | Not used (implicitly matches parent) | Explicitly specifies the foreign namespace
(namespace) |
| Location Attribute | schemaLocation (required in
practice) |
schemaLocation (optional
hint) |
| Primary Use Case | Breaking a single schema into modular files | Reusing external or shared data models across domains |