Can a sequence of XML elements be conditional on a property? Can a sequence of XML elements be conditional on a property? xml xml

Can a sequence of XML elements be conditional on a property?


Turns out, you can do it (sort of) but the method totally sucks.

Had to make two complex types (one with the Approved tag and one without), change the root element and allow switching between the two types like this:

<xs:element name="ArchivedFormulation"> <xs:complexType>  <xs:choice>    <xs:element name="ApprovedFormulation" type="ApprovedFormulation" />    <xs:element name="NonApprovedFormulation" type="NonApprovedFormulation" />  </xs:choice></xs:complexType>

Could add the complex types using XSD inheritance.

<xs:complexType name="ApprovedFormulation"><xs:complexContent>  <xs:extension base="NonApprovedFormulation">    <xs:sequence>      <xs:element name="Approved" minOccurs="1" maxOccurs="1">        <xs:complexType>          <xs:sequence>            <xs:element name="ApprovedBy" type="xs:string" />            <xs:element name="ApprovedOn" type="xs:date" />          </xs:sequence>          <xs:attribute name="IsApproved" type="xs:boolean" />        </xs:complexType>      </xs:element>    </xs:sequence>  </xs:extension></xs:complexContent>

That gave me what I wanted.


A slightly simpler method would be to signal the Boolean value not with an Approved attribute whose value is either true or false, but with an empty Approved element which is either present or absent.

<xs:element name="Formulation">  <xs:complexType>    <xs:sequence minOccurs="0">      <xs:element ref="Approved"/>      <xs:element ref="By"/>      <xs:element ref="Date"/>    </xs:sequence>  </xs:complexType></xs:element>

Now your two examples look like this:

<Formulation/><Formulation>  <Approved/>  <By>RT</By>   <Date>27/07/2011</Date></Formulation>