user972391
user972391

Reputation: 321

Make an element optional/mandatory based on another element using xsd:assert

I believe XSD 1.1 has asserts that allows conditional logic.

I have a schema like this:

        <xs:element minOccurs="0" maxOccurs="1" name="Type" type="xs:integer" />
        <xs:element minOccurs="0" maxOccurs="1" name="Comment" type="xs:string" />

I want the Comment section to be mandatory only if the Type is 0. If Type is anything else, I want the Comment element to be optional.

How do I achieve this using asserts?

Upvotes: 1

Views: 4202

Answers (2)

kjhughes
kjhughes

Reputation: 111726

Credit: Michael Kay, George Boole, and Augustus De Morgan.

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
           vc:minVersion="1.1">

  <xs:element name="root">
    <xs:complexType>
      <xs:sequence>
        <xs:element minOccurs="0" maxOccurs="1" name="Type" type="xs:integer" />
        <xs:element minOccurs="0" maxOccurs="1" name="Comment" type="xs:string" />
      </xs:sequence>
      <xs:assert test="Comment or not(Type = 0)"/>
    </xs:complexType>
  </xs:element>

</xs:schema>

Upvotes: 2

Michael Kay
Michael Kay

Reputation: 163595

test="not(Type=0 and not(Comment))"

Upvotes: 4

Related Questions