ilomambo
ilomambo

Reputation: 8350

XSD Specifying an attribute that can be used only once in the XML

Having a complexType with several attributes:

<xs:complexType name="baseType" mixed="true">
    <xs:attribute name="name" type="xs:string" use="required"/>
    <xs:attribute name="leader" type="xs:boolean" use="optional"/>
</xs:complexType>
<xs:element name="person" type="baseType"/>

How can I restrict the leader attribute to be used only once in the XML file? so the following will not validate (cannot be two leaders)

<person name="Charlie"/>
<person name="Megan" leader="true"/>
<person name="Moe"/>
<person name="Jonathan" leader="true"/>
<person name="Claire"/>

Upvotes: 3

Views: 820

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122374

You can enforce "at most once" if you give the leader attribute a type that has only one possible value (e.g. a type that derives by restriction from boolean and allows only true), then add a unique constraint at the level of the parent element that contains the person elements, stating that person elements must have unique values of their leader attribute. Since unique constraints only apply to elements where the field is actually present, this will ensure that no more than one person has a leader attribute, and when that attribute is present it must be true.

I don't think there's a way to enforce "at least one" in XML Schema 1.0, you could do it with an assertion if you can use 1.1.

Upvotes: 3

Related Questions