2

Basically I have my XML version 1.0 and I have a complex element with following example:

<tile>
  <position>5</position>
  <type>floor</type>
  <towerPlacement>true</towerPlacement>
</tile>

I have defined following in my XML Schema:

<xs:element name="type">
   <xs:simpleType>
   <xs:restriction base="xs:string">
   <xs:enumeration value="road"/>
   <xs:enumeration value="floor"/>
   <xs:enumeration value="startPos"/>
   <xs:enumeration value="endPos"/>
   </xs:restriction>
   </xs:simpleType>
</xs:element>

Is there a way to make my towerPlacement true only if type = floor?

<xs:element type="xs:boolean" name="towerPlacement" minOccurs="0" maxOccurs="1" />
kjhughes
  • 106,133
  • 27
  • 181
  • 240
Cows42
  • 307
  • 3
  • 12

1 Answers1

2

XSD 1.0

Your constraint cannot be expressed in XSD 1.0.

XSD 1.1

Your constraint can be expressed in XSD 1.1 using an assertion to state that towerPlacement must only be true if type = 'floor':

<?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="tile">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="position" type="xs:integer"/>
        <xs:element name="type">
          <xs:simpleType>
            <xs:restriction base="xs:string">
              <xs:enumeration value="road"/>
              <xs:enumeration value="floor"/>
              <xs:enumeration value="startPos"/>
              <xs:enumeration value="endPos"/>
            </xs:restriction>
          </xs:simpleType>
        </xs:element>
        <xs:element name="towerPlacement" type="xs:string"/>
      </xs:sequence>
      <xs:assert test="(type='floor' and towerPlacement='true') 
                       or towerPlacement!='true'"/>
    </xs:complexType>
  </xs:element>
</xs:schema>
kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • Thank you, seems to be working now. I had done this earlier but, managed to place the assert in wrong place :/ – Cows42 Dec 07 '17 at 13:41
  • Nvm.. I placed the assert there and then complexType turned red with error saying it is invalid content. I don't know which XSD version I have since I auto-generated in IntelliJ. What do you think? @kjhughes – Cows42 Dec 07 '17 at 13:46