5

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 ?

Aarish Ramesh
  • 6,745
  • 15
  • 60
  • 105

1 Answers1

6

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

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • I need to reference complex types from other namespace as well. Can you help me with the code for that ? – Aarish Ramesh Dec 06 '17 at 22:47
  • 1
    I've added a link to a complete, working example of how to use `xsd:import`. – kjhughes Dec 06 '17 at 22:58
  • I am getting this error while trying to reference complex type student in teacher "Invalid attribute value for 'ref' in element 'element'. Recorded reason: UndeclaredPrefix: Cannot resolve 'student:student' as a QName: the prefix 'student' is not declared" . Can you please check? – Aarish Ramesh Dec 06 '17 at 23:16
  • Hi, I have asked another question https://stackoverflow.com/questions/47685305/import-complex-types-from-xsd-in-different-namespace . Can you please look into it ? Thanks a lot – Aarish Ramesh Dec 06 '17 at 23:39