Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Schema - Dynamic maxOccurs? [duplicate]

I have an XSD to validate an XML file. The structure is as follows:

<root>
    <child>
        <size>2</size>
        <childElement>Element 1</childElement>
        <childElement>Element 2</childElement>
    </child>
</root>

The number of childElements is dependent on the size provided i.e. if size was set as 3, not more than 3 childElements can be added.

I have tried using xs:alternative but it does not seem to work:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="root">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="child" minOccurs="1" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="size" type="xs:integer" maxOccurs="1"/>
                            <xs:element name="childElement" type="xs:string" maxOccurs="1">
                                <xs:alternative test="@size>1" maxOccurs="@size"/>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Is there a way of using xs:alternative or another tag to achieve this, or is this outside the realm of possibility with XSD?

like image 999
SelketDaly Avatar asked Mar 15 '26 22:03

SelketDaly


1 Answers

Design recommendation: If your XML design can still be changed, eliminate the size element and convey that information implicitly rather than explicitly. By eliminating the duplication of information, you'll not need to check that the duplication is consistent.

If your XML design cannot still be changed, or if you choose not to change it...

XSD 1.0

Not possible. Would have to be checked out-of-band wrt XSD.

XSD 1.1

Possible using xs:assert:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" 
           elementFormDefault="qualified" 
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
           vc:minVersion="1.1">
  <xs:element name="root">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="child">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="size" type="xs:integer"/>
              <xs:element name="childElement" maxOccurs="unbounded"/>
            </xs:sequence>
            <xs:assert test="count(childElement) = size"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
like image 183
kjhughes Avatar answered Mar 18 '26 21:03

kjhughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!