Setting minOccurs and maxOccurs in XSD based on va

2019-01-20 04:24发布

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?

1条回答
做自己的国王
2楼-- · 2019-01-20 05:19

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>
查看更多
登录 后发表回答