'How to add element conditionally to XSD based on the value of another element

I have a scenario, where the first element (Mode) can have a value of either Add/Edit/Delete.

Now, I need to have another element (ID) based on the value of the first element.

if the first element value is Add then the XML validation should fail if the second element exists.

if the first element value is either Edit/Delete then the second element is required in the XML for the validation to pass.

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:simpleType name="mode">
        <xs:restriction base="xs:string">
            <xs:enumeration value="Add"/>
            <xs:enumeration value="Edit"/>
            <xs:enumeration value="Delete"/>
        </xs:restriction>
    </xs:simpleType>
<xs:element name="Request">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="Mode" type="mode" minOccurs="1"></xs:element>
            <xs:element name="ID" type="xs:string" minOccurs="0"></xs:element>
        </xs:sequence>
        <xs:assert test="not(Mode != 'Add') or ID"/>
    </xs:complexType>
</xs:element>

I tried adding xs:assert to add conditional validation but I'm getting the below error

The 'http://www.w3.org/2001/XMLSchema:assert' element is not supported in this context.



Solution 1:[1]

xs:assert is only available in XSD 1.1, which .NET does not support. For XSD 1.1, use Saxon instead.

XSD 1.0 solution

Content model constraints in XSD 1.0 are based on component names. You'll have to redesign your XML to represent Add vs Edit vs Delete as elements rather than as attribute values to express ID's different occurrence constraints depending on request type.

Rather than

<Request>
  <Mode>Add</Mode>
</Request>

<Request>
  <Mode>Edit</Mode>
  <ID>1</ID>
</Request>

<Request>
  <Mode>Del</Mode>
  <ID>2</ID>
</Request>

use

<Add></Add>

<Edit>
  <ID>1</ID>
</Edit>

<Del>
  <ID>2</ID>
</Del>

This design can easily be accommodated in XSD 1.0.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kjhughes