XML schema - only one element must have an attribute equal to true

How can I define a boolean attribute that can be set to true in only one element. The following snippet must be invalid.

<products> <product featured="yes">Prod 1</product> <product featured="yes">Prod 2</product> </products> 
+7
attributes schema xsd
source share
5 answers

You cannot do this with XML Schemas.

You can define attributes for an element, but not limit them to one instance of the element.

+5
source share

You can add an attribute to the products element indicating where product .

+4
source share

You cannot do this with XMLSchema. If you want to specify these restrictions in an XML environment, try Schematron ( http://www.schematron.com/ ).

+3
source share

You can do the following ...

 <products> <product featured="Yes">Prod 1</product> <product>Prod 2</product> </products> 

Then use a unique element to limit the attribute this way ...

 <xs:unique name="UniqueFeaturedProduct"> <xs:selector xpath="product"/> <xs:field xpath="@featured"/> </xs:unique> 

If you were to restrict the "featured" attribute to an optional enumeration of a single "Yes" value, then there can only be one attribute attribute. Something like that...

 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:element name="products"> <xs:complexType> <xs:sequence> <xs:element name="product" type="productType" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:unique name="UniqueFeaturedProduct"> <xs:selector xpath="product"/> <xs:field xpath="@featured"/> </xs:unique> </xs:element> <xs:simpleType name="featuredType"> <xs:restriction base="xs:string"> <xs:enumeration value="Yes"/> </xs:restriction> </xs:simpleType> <xs:complexType name="productType"> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="featured" type="featuredType" use="optional"/> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:schema> 
+2
source share

My answer is this because I cannot add comments yet.

"You can add an attribute to the product item indicating which product is listed."

This solution leads to another problem: checking if the attribute points to an existing element.

 <products featured_id="3"> <product id="1">Prod 1</product> <product id="2">Prod 2</product> </products> 
0
source share

All Articles