I’m trying to extend a complex type to change its minOccurs value, I tried different things unsuccessfully, here is my base type:
<xs:complexType name="PhoneNumberType">
<xs:sequence>
<xs:element name="AreaCode">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]+" />
<xs:maxLength value="3" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="LocalNumber">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]+" />
<xs:minLength value="7" />
<xs:maxLength value="17" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Extension" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]+" />
<xs:maxLength value="5" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
First I tried this to make AreaCode optionnal for particular situations:
<xs:element name="PhoneNumberWithOptionalAreaCode">
<xs:complexType>
<xs:complexContent>
<xs:extension base="PhoneNumberType">
<xs:sequence>
<xs:element name="AreaCode" type="xs:string" minOccurs="0" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:element>
It gives me an error saying that elements with same name should have the same type.
So I tried this:
<xs:complexType name="PhoneNumberType">
<xs:sequence>
<xs:element name="AreaCode" type="AreaCodeType" />
<xs:element name="LocalNumber">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]+" />
<xs:minLength value="7" />
<xs:maxLength value="17" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Extension" minOccurs="0">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]+" />
<xs:maxLength value="5" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="AreaCodeType">
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]+" />
<xs:maxLength value="3" />
</xs:restriction>
</xs:simpleType>
<xs:element name="PhoneNumberWithOptionalAreaCode">
<xs:complexType>
<xs:complexContent>
<xs:extension base="PhoneNumberType">
<xs:sequence>
<xs:element name="AreaCode" type="AreaCodeType" minOccurs="0" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
</xs:element>
Now the xsd is valid, but when I try to validate the following xml it says LocalNumber is not expected, expected AreaCode.
<PhoneNumberWithOptionalAreaCode>
<LocalNumber>1234567</LocalNumber>
</PhoneNumberWithOptionalAreaCode>
Can anyone help please ?
Thanks !
You cannot use neither extension/restriction to make a mandatory element optional in the lower hierarchy. See the XML Schema specification more on this:Restriction
Only possible solution would be invert the hierarchy if you have control. Make
PhoneNumberWithOptionalAreaCodeas base and havePhoneNumberTypeextend thePhoneNumberWithOptionalAreaCode