简体   繁体   中英

How to define elements in xsd as mandatory/optional and any order

I am unable to define the elements with <xsd:all> for below requirement,

I am getting error that maxOccursv should be 0 or 1 under schema all`.

Below is my requirement, could anyone please help me as soon as possible.

  1. elements ( A & B ) can come in any order in xml (so i am using xsd:all , but gettting error), i don't want to go with sequence.
  2. element A is mandatory, it should appear in xml always, however element B is optional.
  3. element A & B can appear any number of times for example I can have element A 10 times and element B 20 times.

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="InvoiceData">
        <xsd:complexType>
            <xsd:all>
                <xsd:element name="A" minOccurs="1" maxOccurs="unbounded" >
                <xsd:element name="B" minOccurs="0" maxOccurs="unbounded" >
            </xsd:all>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

In XSD 1.1 you can use xs:all with maxOccurs values other than 0 or 1.

In XSD 1.0 the nearest you can get is the model (A|B)*, but you can't then impose different maxOccurs values for A and B.

Like Dr. Kay said, you can't use <xsd:all> for such problem in XSD 1.0. Instead, you need to modify your answer to use sequences and choices.

This XSD 1.0 code should match your three requirements: order is free, <A> is mandatory and maximum occurences are both unbounded.

<xsd:element name="InvoiceData" >
    <xsd:complexType>
        <xsd:choice>
            <xsd:sequence>
                <xsd:element name="B" minOccurs="0"/>
                <xsd:element name="A"/>
            </xsd:sequence>
            <xsd:choice minOccurs="0" maxOccurs="unbounded">
                <xsd:element name="A"/>
                <xsd:element name="B"/>
            </xsd:choice>
        </xsd:choice>
    </xsd:complexType>
</xsd:element>

If I understand the question correctly, you want a mix of A and B elements; A must occur at least once, B need not appear at all; neither has a maximum. (If Michael Kay is right to think you do want to impose maximum occurrence counts on A and B, then things get more complicated.)

In DTD notation, (a*, (b, a*)+) does the trick. In XSD notation:

<xsd:sequence>
  <xsd:element ref="A" 
               minOccurs="0" 
               maxOccurs="unbounded"/>
  <xsd:sequence maxOccurs="unbounded">
    <xsd:element ref="B"/> 
    <xsd:element ref="A" 
                 minOccurs="0" 
                 maxOccur="unbounded"/>
  </
</

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM