Eric H.
Eric H.

Reputation: 2232

XSD : how to validate this xml, with sequences depending on the value of the first one?

I have 3 kinds of XML blocks, containing no "filter" block, or "filter" with "invalidation" whose first value is either "fixed1" or "fixed2"; if "fixed1": nothing else, if "fixed2", this sequence A1,A2,A3 (see below) :

        <filter>
          <invalidation>fixed1</invalidation>
        </filter>

        <filter>
          <invalidation>fixed2</invalidation>
          <A1>string...</A1>
          <A2>string...</A2>
          <A2>string...</A3>
        </filter>

How to validate this ? I feel that there is some solution using xs:choice, but I couldn't find.

The only (poor) solution I found is :

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
...
<xs:simpleType name="invalidation">
  <xs:restriction base="xs:string">
    <xs:pattern value="fixed1|fixed2"/>
  </xs:restriction>
</xs:simpleType>
...
<xs:element name="filter" minOccurs="0">
  <xs:complexType>
    <xs:all>
      <xs:element name="invalidation" type="invalidation"/>
      <xs:element name="A1" type="xs:string" minOccurs="0"/>
      <xs:element name="A2" type="xs:string" minOccurs="0"/>
      <xs:element name="A3" type="xs:string" minOccurs="0"/>
    </xs:all>
  </xs:complexType>
</xs:element>

Upvotes: 0

Views: 75

Answers (1)

Michael Kay
Michael Kay

Reputation: 163360

This cannot be done in XSD 1.0.

It can be done in XSD 1.1 using assertions. Define the structure as a sequence with the content model (invalidation, (A1, A2, A3)?) and then define an assertion: not(invalidation='fixed1' and exists(A1)).

XSD 1.1 is supported in Altova, Saxon, and Apache Xerces, but not in other products such as the built-in validators in Java and .NET.

Upvotes: 1

Related Questions