How to choose one and only one element in an XML Schema definition
apologies if this has been asked before but I have searched the site...
Anyway, I have been trying to work out how to enforce the choice of one and only one element in an XML Schema.
For instance, say you need to choose between only one apple, orange or banana element, but you cannot have NO apples, oranges or banana elements.
Now I've tried this:
<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://tempuri.org/Fruit"
xmlns="http://tempuri.org/Fruit"
elementFormDefault="qualified">
<xsd:complexType mixed="true">
<xsd:sequence>
<xsd:choice minOccurs="0" maxOccur开发者_运维知识库s="1">
<xsd:element name="banana" type="xsd:string"/>
<xsd:element name="apple" type="xsd:string"/>
<xsd:element name="orange" type="xsd:string"/>
</xsd:choice>
</xsd:sequence>
</xsd:complexType mixed="true">
</xsd:schema>
Now this is great, however <choice>
is not one and only one but is actually zero or only one. How would I enforce the cardinality to be one and only one in an XML Schema Definition file?
In this way:
<xsd:choice minOccurs="1" maxOccurs="1">
Modified schema: I added Fruit - root and changed xsd to xs
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">
<xs:element name="Fruit">
<xs:complexType mixed="true">
<xs:sequence>
<xs:choice minOccurs="1" maxOccurs="1">
<xs:element name="banana" type="xs:string"/>
<xs:element name="apple" type="xs:string"/>
<xs:element name="orange" type="xs:string"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
@smas' response is correct. However, both minOccurs and maxOccurs attributes default to 1 when not explicitly declared in xs:choice (source). So you could just get rid of the attributes on xs:choice and get the behavior you want.
精彩评论