1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Is there anyway without assert? Also, is XSD 1.1 is supported by major processor? I tried using assert in Visual Studio 2013, but it didn't work. Any free tools where I can verify XML against XSD 1.1 schema?
As I mentioned, you'll need XSD 1.1 if you want to do it within XSD. For a list of processors that support XSD 1.1, see this answer. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.