I have a shared XML schema which has not namespace declared department.xsd
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
attributeFormDefault="unqualified"
version="1-0">
<xs:complexType name="Department">
<xs:sequence>
<xs:element name="Name"/>
<xs:element name="Manager"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
And I want to import Department.xsd in Company.xsd which has the namespace MainNameSpace
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="MainNameSpace"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:m="MainNameSpace" <!--New NameSpace-->
targetNamespace="MainNameSpace"
elementFormDefault="unqualified"
attributeFormDefault="unqualified">
<xs:import schemaLocation="Department.xsd" namespace="MainNameSpace"/> <!--Not working-->
<!--<xs:import schemaLocation="Department.xsd"/> Not working-->
<!--<xs:include schemaLocation="Department.xsd"/> Not working-->
<xs:element name="company" type="Company"/>
<xs:complexType name="Company">
<xs:sequence>
<xs:element name="Name" type="xs:string"/>
<xs:element name="Department" type="m:Department"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
However when I compile the schema in C#, I got error “‘Type ‘MainNameSpace:Department’ is not declared.'”. From what I read, include another schema without namespace will use the root namespace for the imported schema, but why MainNameSpace:Department cannot be found?
var schema = new XmlSchemaSet();
schema.Add(null, Path.Combine(baseDirectory, "Department.xsd"));
schema.Add(null, Path.Combine(baseDirectory, "Company.xsd"));
schema.Compile();
In general you should use xs:include
to incorporate a schema document for the same target namespace, and xs:import
to incorporate a schema document for a different target namespace.
However, there is a feature called “chameleon include” which allows a schema document with target namespace N
to xs:include
a no-namespace schema S
, in which case all the declarations in S
are treated as being in the namespace N
. You appear to be using this feature here. This will move the Department
type into the namespace MainNameSpace
, which means that you need to write type="m:Department"
when referencing it, and to add xmlns:m="MainNameSpace"
to the xs:schema
element.
3