Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make type depend on attribute value using Conditional Type Assignment

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'd like to make an XSD, so that if the value of the attribute "type" is 1, the name and surname elements must be present, and when it's 2, name and id must be there. I tried to generate the XSD in XSD schema generator, but it made the surname and id element minOccurs=0. How could I make it work?

like image 676
DropDropped Avatar asked Jan 10 '15 16:01

DropDropped


1 Answers

You can do this using XSD 1.1's 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>
like image 188
kjhughes Avatar answered Oct 12 '22 23:10

kjhughes