Search code examples
xmlxsdxsd-validationxml-validation

Import complex types from another XSD


I am finding difficulty in importing and referencing a complex type from one XSD file to another. Let me illustrate my scenario with an example

Student.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="xyz"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:common="xyz"
    xmlns="xyz"
    elementFormDefault="qualified">

    <xsd:element name="student" type="student" />

    <xsd:complexType name="student">
        <xsd:sequence>
            <xsd:element name="id" type="xsd:string" />
            <xsd:element name="birth-date" type="xsd:date" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:schema>

Here is another XSD, Teacher.xsd, where I would like to reference the complex type student from student.xsd

Teacher.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="xyz"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:common="xyz"
    xmlns="xyz"
    elementFormDefault="qualified">

    <xsd:import schemaLocation="student.xsd"
        namespace="xyzzz" />

    <xsd:element name="teacher" type="teacher" />

    <xsd:complexType name="teacher">
        <xsd:sequence>
            <xsd:element name="id" type="xsd:string" />
            <xsd:element name="name" type="xsd:string" />

            // TODO - Refer to student from student.xsd

        </xsd:sequence>
    </xsd:complexType>

</xsd:schema>

I have seen other Stack Overflow posts regarding the syntax for achieving this like

<xs:element name="teacher" type="teacher:teacher"/>

along with import:

<xsd:import schemaLocation="xyz" namespace="xyz"/>

but nothing seems to be working.

Can someone help me achieve this ?


Solution

  • Use xsd:include rather than xsd:import since the XSDs are in the same namespace.

    Notes

    • You'll want to include Student.xsd, not common.xsd.
    • Since the type being referenced is in the same namespace, you don't need to specify a namespace prefix:

      <xsd:element name="student" type="student"/>
      
    • It's better style to name your elements and attributes differently.

    See also