Search code examples
c#xsd

When adding Schema to XmlSchemaSet, I get an exception


I have this XSD I made

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xsd:complexType name="FunnyType">
        <xsd:element name="Prueba1" type="xsd:string"/>
        <xsd:element name="Prueba2" type="xsd:int"/>
    </xsd:complexType>
    <xsd:element name="Funnys">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="funny" type="FunnyType" minOccurs="0"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

Which gives me a System.Xml.Schema.XmlSchemaException: 'http://www.w3.org/2001/XMLSchema:element' is invalid in this context. (not the exact error, I translated it from spanish).

I have gone up and down everywhere (here, asking colleagues, etc) and made changes to the file, yet I cannot find the error.

What am I lacking here that makes c# throw an exception?

Thank you


Solution

  • You can't have this:

    <xsd:complexType name="FunnyType">
      <xsd:element name="Prueba1" type="xsd:string" />
      <xsd:element name="Prueba2" type="xsd:int" />
    </xsd:complexType>
    

    You have to begin the complexType with one of the 3 compositors: xsd:sequence, xsd:all or xsd:choice:

    For example:

    <xsd:complexType name="FunnyType">
      <!-- Can also be xsd:all or xsd:choice -->
      <xsd:sequence> 
        <xsd:element name="Prueba1" type="xsd:string" />
        <xsd:element name="Prueba2" type="xsd:int" />
      </xsd:sequence>
    </xsd:complexType>
    

    You need to decide which one to use that best suits what your complex type is meant to model.