Search code examples
xmlxsdxsd-validationxml-validation

Using XSD to validate one element, or other element, or both


I'm using an XSD file and C# .NET to validation XML. I need to validate the <Message> element has either:

<Edit> OR <Delete> OR <Edit> <Delete> (IE both elements)

Can this be done in XSD?


Solution

  • Yes, this XSD,

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="Message">
        <xs:complexType>
          <xs:choice>
            <xs:sequence>
              <xs:element name="Edit"/>
              <xs:element name="Delete" minOccurs="0"/>
            </xs:sequence>
            <xs:element name="Delete"/>
          </xs:choice>
        </xs:complexType>
      </xs:element>
    </xs:schema>
    

    will allow <Edit/> or <Delete/> or <Edit/><Delete/>, as requested.