-->

What is the alternative to have xsd:sequence behav

2019-02-18 19:06发布

问题:

I don't understand how I should define my complex type.

Today I have this:

<xsd:element name="batch_requests_callbacks">
    <xsd:complexType>
      <xsd:sequence>
            <xsd:element ref="document_id" minOccurs="1" maxOccurs="1"/>
            <xsd:choice minOccurs="0" maxOccurs="1">
              <xsd:element ref="filename"/>
              <xsd:element ref="error"/>
            </xsd:choice>
            <xsd:element ref="author" minOccurs="0" maxOccurs="unbounded"/>
      </xsd:sequence>
      <xsd:attribute name="version" default="1.0"/>
    </xsd:complexType>
</xsd:element>

But then, the tag's order inside the xsd:sequence is important and I don't want that behavior.

If I use xsd:all I don't have the tag order but I cannot set maxOccurs to unbounded more over I cannot use xsd:choice inside a xsd:all

What are my alternatives?

回答1:

You can use <xsd:choice minOccurs="0" maxOccurs="unbounded"> instead of your xsd:sequence in order to emulate non-ordered element validation. This circumvents the limitations of xsd:all.



回答2:

In XSD 1.0, your alternatives are (if you want to keep things simple) as you have identified them:

  • sequence, which requires a particular ordering
  • all, which does not.

If the ordering does not carry meaning (so the sequence document-id, filename, author and the sequence author, document-id, filename carry the same information), then there is no loss of expressive power in fixing the sequence. Or you can use an unbounded choice, as suggested by predi, and place part of the validation logic (checking cardinality) in another layer of the application. The vocabulary designers I think most highly of generally recommend a sequence in this situation.

Two other approaches are worth mentioning:

  • In XSD 1.1, the constraints on maxOccurs in all-groups have been lifted (though not the other constraints on all-groups).
  • Since the language you want is clearly a regular language, you can write a content model for it using nested choices and sequences. This is made a bit tedious by XSD's 'unique particle attribution' constraint, which means you have to avoid anything that might make the content model non-deterministic, but it's doable. A concrete example is shown in the answer to another question.