How to restrict size of an XML list based on the size of another XML list in XSD?

331 views Asked by At

I have an XML Schema, a snippet of which looks like the one below:

<xs:complexType name="Operation" abstract="true">
    <xs:sequence>
        <xs:element name="id" type="xs:string"/>
        <xs:element name="type" type="xs:string"/>
        <xs:element name="inputFields" minOccurs="0">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="field" type="field" minOccurs="0" maxOccurs="unbounded"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
        <xs:element name="outputFields" minOccurs="1">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="field" type="field"  minOccurs="0" maxOccurs="unbounded"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    </xs:sequence>
</xs:complexType>

I want to put a restriction/validation that the size of the list inputFields and outputFields be equal. How can I achieve that in the XML Schema itself?

1

There are 1 answers

0
kjhughes On

XSD 1.1

You could do this via assertions in XSD 1.1 by constraining the count of the number elements in inputFields and outputFields to be equal:

<xs:assert test="count(inputFields/field) = count(outputFields/field)"/>

You'd place this on the element declaration containing both inputFields and outputFields.

XSD 1.0

You cannot use xs:assert in XSD 1.0 and cannot express your constraint given your current XML design. However, if you instead redesigned your XML to pair input and output fields together in the first place,

            <xs:sequence maxOccurs="unbounded">
                <xs:element name="inputField" type="field"/>
                <xs:element name="outputField" type="field"/>
            </xs:sequence>

you'd naturally constrain their occurrence counts to be equal, and you'd be able to use XSD 1.0.