简体   繁体   中英

XML schema constraint between elements

Suppose I have an XML element which looks like this:

<foo>
    <a>2</a>
    <b>5</b>
</foo>

I would like to express the following constraints with a schema (.xsd):

  1. <foo> has exactly one child <a> and exactly one child <b> , and no other children.

  2. The values of <a> and <b> are integers in interval [1, 10].

  3. The value of <a> is less than or equal to the value of <b> .

I know how to express constraints 1 and 2 with a schema, but not 3.

Any help?

For the 3rd point you can add the following constraint:

<xs:complexType name="foo">
    <xs:sequence>
        <!-- or all if the order is not important -->
        <xs:element name="a" type="xs:integer" maxOccurs="1" minOccurs="1">
            <xs:simpleType>
                <xs:restriction base="xs:integer">
                    <xs:minInclusive value="1"/>
                    <xs:maxInclusive value="10"/>
                </xs:restriction>
            </xs:simpleType>
        </xs:element>
        <xs:element name="b" type="xs:integer" maxOccurs="1" minOccurs="1">
            <xs:simpleType>
                <xs:restriction base="xs:integer">
                    <xs:minInclusive value="1"/>
                    <xs:maxInclusive value="10"/>
                </xs:restriction>
            </xs:simpleType>
        </xs:element>
    </xs:sequence>
    <xs:assert test="a &lt;= b"/> <!-- your 3rd constraint -->
</xs:complexType>

As @Allan says, you can use xs:assert. Though it might be worth mentioning that this requires XSD 1.1, which many schema processors do not support.

In fact, once you're using XSD 1.1, I tend to get lazy and express a lot more of the constraints using xs:assert . I might write this one as:

<xs:complexType name="foo">
    <xs:sequence>
        <xs:element name="a" type="xs:integer"/>
        <xs:element name="b" type="xs:integer"/>
    </xs:sequence>
    <xs:assert test="a = (1 to 10) and b = (1 to 10) and a le b"/>
</xs:complexType>

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