Validate elements in any order and any number of times using XSD

Sometimes you just want to validate any number of elements any number of times. There is no intuitive way in XSD to accomplish this so we have to use a trick to get it to work. The solution looks a little like this:

<xs:element name="myElement">
    <xs:complexType>
      <xs:sequence minOccurs="0" maxOccurs="unbounded">
        <xs:choice>
          <xs:element name="myId" type="xs:int" />
          <xs:element name="myName" type="xs:string" />
        </xs:choice>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

This lets us validate any of the elements in the <choice> (myId and MyName) list any number of times and in any order, so the following will validate:

<myElement>
  <myId>3</myId>
  <myName>Niklas</myName>
</myElement>

and:

<myElement>
  <myName>Niklas</myName>
  <myId>3</myId> 
</myElement>

and:

<myElement>
  <myId>3</myId>
  <myName>Niklas</myName>
  <myName>Anders</myName>
</myElement>

but not:

<myElement>
  <myId>hello</myId>
  <myName>Niklas</myName>
</myElement>

Last one does not validate since ‘hello’ is not a integer.

Tested with xmllint with libxml version 20708

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>