XSD: if an element has a specific meaning, the other should be optional

I have an XML document similar to:

<?xml version="1.0" encoding="UTF-8"?>
<html2filename xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../xsd/mapper.xsd">
    <htmlFile filename="N5670A">
        <variant>1</variant>
        <groups>
            <group>
                <name>Removing thermostat</name>
            </group>
            <someOtherElements>asdasd</someOtherElements>
        </groups>
    </htmlFile>
</html2filename>

      

Now the element "groups" → "group" → "name" → must have one restriction: it must be optional if "variant" is 3. If not, it must be necessary.

Can XSD handle this? If so, how?

+3


source to share


1 answer


XSD 1.1

An xs:assert

can implement such a value-sensitive constraint:

            <xs:assert test="(variant = 3) or groups/group/name"/>

      



Here's in the context of a complete XSD that will validate the provided XML:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" 
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
  vc:minVersion="1.1">
  <xs:element  name="html2filename">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="htmlFile">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="variant"/>
              <xs:element name="groups">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="group" maxOccurs="unbounded">
                      <xs:complexType>
                        <xs:sequence>
                          <xs:element name="name" minOccurs="0"/>
                        </xs:sequence>
                      </xs:complexType>
                    </xs:element>
                    <xs:element name="someOtherElements"/>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
            <xs:attribute name="filename"/>
            <xs:assert test="(variant = 3) or groups/group/name"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
     </xs:complexType>    
  </xs:element>
</xs:schema>

      

+4


source







All Articles