1

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?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
user972391
  • 321
  • 1
  • 4
  • 20

2 Answers2

4
test="not(Type=0 and not(Comment))"
Michael Kay
  • 156,231
  • 11
  • 92
  • 164
  • Correct but reducible: `Comment or Type != 0`. – kjhughes Mar 19 '15 at 12:26
  • It's reducible, but not to that. I think `Comment or not(Type = 0)` would be correct, assuming we read "Type is anything else" to include the case where it is absent. – Michael Kay Mar 19 '15 at 14:56
  • Ah, yes, I think you're right. For example, when both `Comment` and `Type` are absent, `Comment or Type != 0` fails but `Comment or not(Type = 0)` succeeds, which is probably desired. – kjhughes Mar 19 '15 at 15:21
  • Can we apply the same concept for attributes? – Bouramas Nov 30 '17 at 10:32
  • I tried it but it doesn't work. I'm guessing because the attribute has not been defined at the time of the check. It's an attribute of the same element. @MichaelKay – Bouramas Nov 30 '17 at 11:35
  • @Bouramas Your code was wrong. If you need help finding out where it was wrong, raise a new question. – Michael Kay Nov 30 '17 at 11:57
2

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>
kjhughes
  • 106,133
  • 27
  • 181
  • 240