Alex
Alex

Reputation: 2179

Two XML elements with different types repeated unbounded times in XSD?

Suppose I use a sequence of a and b elems. a has a type aType and b has a type bType.

<xs:sequence>
    <xs:element ref="a" maxOccurs="unbounded"/>
    <xs:element ref="b" maxOccurs="unbounded"/>
</xs:sequence>

...

<xs:element name="a" type="aType" abstract="true"/>
<xs:element name="b" type="bType" abstract="true"/>

If I write an XML doc with sequence which has both type elems of aType and bType, I get an error. Is it possible to allow in sequence to use any number of elements of two types? What I want to allow is something like this:

 <seq><a/><a/><b/><a/><b/><b/></seq>

Upvotes: 2

Views: 120

Answers (2)

kjhughes
kjhughes

Reputation: 111686

First, eliminate abstract="true" if you want to instantiate a and b in your document.

Then, place the maxOccurs="unbounded" on xs:choice:

<xs:choice maxOccurs="unbounded">
    <xs:element ref="a"/>
    <xs:element ref="b"/>
</xs:choice>

to allow a and b will be allowed to appear repeatedly such as you show in your comment:

<a/><a/><b/><a/><b/><b/>

Upvotes: 1

C. M. Sperberg-McQueen
C. M. Sperberg-McQueen

Reputation: 25034

The content model you show should match any sequence of one or more elements substitutable for an a element, followed by one or more elements substitutable for b.

You say, however, that you want to match a sequence of a and b elements, intermingled. At least two things in your current declaration will need to change, then:

  • If a and b elements should be allowed to appear in valid document,s then they are not abstract; you should stop saying that they are.

  • If a sequence like <a/><a/><b/> in the input may validly be followed by more a and b elements, then the sequence defined by the xsd:sequence element needs to be allowed to repeat; changing xsd:sequence/@maxOccurs to an integer greater than one, or to unbounded, will be necessary.

  • If the intermingled set of a and b elements can start with a b, or end with an a, then you need to allow the individual elements in the content model to match zero elements in the instance, thus:

    <xs:sequence maxOccurs="unbounded">
      <xs:element ref="a" minOccurs="0" maxOccurs="unbounded"/>
      <xs:element ref="b" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    

    This is equivalent to the content model already suggested by kjhughes; for the language they both recognize, most readers will find a repeating choice clearer than a repeating sequence all of whose members are optional.

Upvotes: 1

Related Questions