Import complex types from another XSD
Asked Answered
S

1

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 ?

Saintpierre answered 6/12, 2017 at 22:26 Comment(0)
H
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

Hydrotaxis answered 6/12, 2017 at 22:36 Comment(4)
I need to reference complex types from other namespace as well. Can you help me with the code for that ?Saintpierre
I've added a link to a complete, working example of how to use xsd:import.Hydrotaxis
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?Saintpierre
Hi, I have asked another question #47685805 . Can you please look into it ? Thanks a lotSaintpierre

© 2022 - 2024 — McMap. All rights reserved.