0

I have an XML file to validate against XSD schema. This is how my XML file looks like.

<service>
  <id>myid</id>
  <name>myname</name>
  <arg>arg1</arg>
  <arg>arg2</arg>
</service>

These are the validation rules.

  • id and name are unique and required. There cannot be more than one element from those.
  • arg can be repeat
  • The order does not matter. Elements can be in any order.

This is the XSD file I created for this.

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="service">
    <xs:complexType>
      <xs:choice maxOccurs="unbounded">

        <xs:element type="xs:string" name="id" minOccurs="1" maxOccurs="1"/>
        <xs:element type="xs:string" name="name" minOccurs="1" maxOccurs="1"/>
        <xs:element type="xs:string" name="arg" minOccurs="1" maxOccurs="unbounded"/>

        </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

When I try to validate with this (https://www.freeformatter.com/xml-validator-xsd.html) online validator this works. But it now shows any error even when there are two id elements or no id element.

<service>
  <id>myid</id>
  <id>anotherid</id>
  <name>myname</name>
  <arg>arg1</arg>
  <arg>arg2</arg>
</service>

This should be wrong since there are two id elements. How to have both repeatable and not repeatable elements in choice elements. Sequence is not possible here since the order does not matter.

<service>
  <name>myname</name>
  <arg>arg1</arg>
  <arg>arg2</arg>
</service>

This should fail since the id element is not there.

potame
  • 7,597
  • 4
  • 26
  • 33
Buddhika Chathuranga
  • 1,334
  • 2
  • 13
  • 22
  • Have you tried using xs:group? – Bryn Lewis Aug 20 '20 at 07:10
  • @BrynLewis even inside `group` doesn't I have to use `choice`? – Buddhika Chathuranga Aug 20 '20 at 07:31
  • I don't think this is achievable without changing the xml data structure. If you use the ```xs:sequence``` option all elements must be in order. If you use the ```xs:choice``` option with the ```maxoccurs``` restriction it will create as much elements that the maxxoccurs is set on. the ```xs:all``` option also gives you the freedom to have elements in a random order. but the ```maxoccurs``` restriction is not possible here. The solution could be a type that holds the unbounded arg element and assign an element to that resulting into a structure. – martijn Aug 20 '20 at 09:38

1 Answers1

0

You have to make a choice. If you allow the elements to be in any order (using UnorderedSet) then you are not allowed to set maxOccurs > 1. If you use a repeating choice, you cannot validate the number of occurrences because you match one occurrence of the tag for each occurrence of the choice. But if you use a sequence, you have to accept that the tags must be in the correct order. Almost everybody just accepts the need for ordered tags in XML - even though it is inconvenient.

kimbert
  • 2,376
  • 1
  • 10
  • 20