Search code examples
xmlxsdxml-namespacesxml-validation

XSD with separated complex types using targetNamespace


I wrote a very simple XML:

<?xml version="1.0" encoding="utf-8"?>
<something attribute1="21" attribute2="23">
  <newelement code="code1"/>
</something>

And I wanted to write an XSD to validate this XML, which works perfectly:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="something">
        <xs:complexType>
            <xs:sequence>
                <xs:element minOccurs="0" name="newelement" nillable="true">
                    <xs:complexType>
                        <xs:attribute type="xs:string" name="code"/>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
            <xs:attribute name="attribute1" type="xs:int"/>
            <xs:attribute name="attribute2" type="xs:int"/>
        </xs:complexType>
    </xs:element>
</xs:schema>

But then I wanted to write the same XSD, but with separated complex types, because for example, what if I will need that same structure as the newelement has now. So I refactored my XSD this way:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema targetNamespace="my-common-types"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:tns="my-common-types">
    <xs:element name="something">
        <xs:complexType>
            <xs:sequence>
                <xs:element minOccurs="0" name="newelement" nillable="true" type="tns:ElementWithCode"/>
            </xs:sequence>
            <xs:attribute name="attribute1" type="xs:int"/>
            <xs:attribute name="attribute2" type="xs:int"/>
        </xs:complexType>
    </xs:element>

    <xs:complexType name="ElementWithCode">
        <xs:attribute name="code" type="xs:string"/>
    </xs:complexType>
</xs:schema>

And then, I always get this error:

ERROR: Element 'something': No matching global declaration available for the validation root.

So there is a problem using targetNamespace attribute on the scheme, but I don't get it how could I make this working. Please give me some advises. Thank you!


Solution

  • There were missing parts from both XML and XSD.

    XML was missing the xmlns="my-common-types" attribute from the <something> element.

    XSD was missing the elementFormDefault="qualified" attribute from <xs:schema> element.