Search code examples
xmlxsd

XML XSD: Extendending complex type from imported XSD


I want to extend a complex type which is defined in an imported XSD. I set up the following example:

Base.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.com/base">
    <xs:complexType name="BaseType">
        <xs:sequence>
            <xs:element name="baseElement" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:schema>

Extended.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:base="http://www.example.com/base"
    xmlns="http://www.example.com/extended"
    targetNamespace="http://www.example.com/extended">

    <xs:import namespace="http://www.example.com/base" schemaLocation="Base.xsd" />   
    <xs:complexType name="ExtendedType">
        <xs:complexContent>
            <xs:extension base="base:BaseType">
                <xs:sequence>
                    <xs:element name="extendedElement" type="xs:int" />
                </xs:sequence>
            </xs:extension>
        </xs:complexContent>
    </xs:complexType>

    <xs:element name="ExtendedElement" type="ExtendedType" />
</xs:schema>

Example.xml

<?xml version="1.0" encoding="UTF-8"?>
<extended:ExtendedElement xmlns:extended="http://www.example.com/extended"
    xmlns="http://www.example.com/base"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.example.com/extended extended.xsd
                                         http://www.example.com/base base.xsd">
                                         
    <baseElement>someString</baseElement>
    <extendedElement>3</extendedElement>
</extended:ExtendedElement>

Now the problem with this XML is: I get a validation error that one of the elements "baseElement" is expected (even though the error is shown at exactly this element). Is there anything wrong with the XSD definition?


Solution

  • The validation error specifies that it doesn't expect a namespace qualified element in the XML :

    Invalid content was found starting with element '{"http://www.example.com/base":baseElement}'. One of '{baseElement}' is expected.

    Since you defined the unqualified namespace xmlns="http://www.example.com/base" to point to http://www.example.com/base, every unqualified XML tags will be bound to this.

    By changing this to xmlns:base="http://www.example.com/base" named-namespace, it should work