...">

How to make a type dependent on an attribute value by assigning a conditional type

I have an XML file like this

<listOfA>
  <a type="1">
    <name></name>
    <surname></surname>
  </a>
  <a type="2">
    <name></name>
    <id></id>
  </a>
</listOfA>

I would like to make XSD, so if the value of the "type" attribute is 1, then the elements of the name and surname should be present, and with its 2 - the name and identifier. I tried to generate XSD in the XSD schema generator , but it made the last name and id element minOccurs = 0. How can I make it work?

+4
source share
1 answer

You can do this using XSD 1.1 Conditional type assignment :

<?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"
           elementFormDefault="qualified"
           vc:minVersion="1.1"> 
  <xs:element name="listOfA">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="a" maxOccurs="unbounded">
          <xs:alternative test="@type = 1" type="a1Type"/>        
          <xs:alternative test="@type = 2" type="a2Type"/>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:complexType name="a1Type">
    <xs:sequence>
      <xs:element name="name"/>
      <xs:element name="surname"/>
    </xs:sequence>
  </xs:complexType>
  <xs:complexType name="a2Type">
    <xs:sequence>
      <xs:element name="name"/>
      <xs:element name="id"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>
+6
source

Source: https://habr.com/ru/post/1570711/


All Articles