Reputation: 980
I have a XML which reads
<Options>
<option1>Y</option1>
<option2>N</option2>
<option3>N</option3>
</Options>
I would like to ensure only one child element (of Options) has value Y so that above XML is valid but not the below one.
<Options>
<option1>Y</option1>
<option2>Y</option2>
<option3>N</option3>
</Options>
I tried unique and referential integrity but couldn't work out.
Any help/idea much appreciated.
Upvotes: 1
Views: 1069
Reputation: 111716
You'd have to enforce such a constraint outside of XSD 1.0, but you could use xs:assert
to enforce it with XSD 1.1:
<?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="Options">
<xs:complexType>
<xs:sequence>
<xs:element name="option1"/>
<xs:element name="option2"/>
<xs:element name="option3"/>
</xs:sequence>
<xs:assert test="count(* = 'Y') = 1"/>
</xs:complexType>
</xs:element>
</xs:schema>
Or, to avoid separately naming each option
:
<?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="Options">
<xs:complexType>
<xs:sequence>
<xs:element name="option" maxOccurs="unbounded" />
</xs:sequence>
<xs:assert test="count(option = 'Y') = 1"/>
</xs:complexType>
</xs:element>
</xs:schema>
Constraining options to be only Y
or N
could of course also been done if desired.
Upvotes: 1