Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML XSD Schema - Enforce Unique Attribute Values in Schema

Lets say I have a schema that defines the following XML:

<Values>     <Add Key="Key1">Value 1</Add>     <Add Key="Key2">Value 2</Add>     <Add Key="Key3">Value 3</Add>     <Add Key="Key4">Value 4</Add> </Values> 

I would like, at a schema level, to be able to enforce that the values for the Key attribute are unique, i.e. the example above is valid, but the following example would be invalid:

<Values>     <Add Key="Key1">Value 1</Add>     <Add Key="Key2">Value 2</Add>     <Add Key="Key2">Value 3</Add>     <Add Key="Key3">Value 4</Add> </Values> 

Notice that there are two Add elements with a Key of Key2

For reference here is the simple schema:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">     <xs:element name="Values">         <xs:complexType>             <xs:sequence>                 <xs:element name="Add" maxOccurs="unbounded">                     <xs:complexType>                         <xs:simpleContent>                             <xs:extension base="xs:string">                                 <xs:attribute name="Key" type="xs:token" use="required"/>                             </xs:extension>                         </xs:simpleContent>                     </xs:complexType>                 </xs:element>             </xs:sequence>         </xs:complexType>     </xs:element> </xs:schema> 

I am under the impression that this is not possible at a schema level, however I am all ears.

like image 351
MrEyes Avatar asked Apr 04 '11 16:04

MrEyes


People also ask

What is unique attribute in XML?

The unique element defines that an element or an attribute value must be unique within the scope. The unique element MUST contain the following (in order): one and only one selector element (contains an XPath expression that specifies the set of elements across which the values specified by field must be unique)

What is elementFormDefault in XSD?

elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (. xml file), rather than namespaces in the schema document itself (. xsd file). By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.


1 Answers

@BatteryBackupUnit has the right idea, but the syntax is more like:

<xs:element name="Values">   <xs:complexType>     <xs:sequence>       <xs:element ref="Add" maxOccurs="unbounded"/>     </xs:sequence>   </xs:complexType>   <xs:unique name="UniqueAddKey">     <xs:selector xpath="Add" />      <xs:field xpath="@Key" />    </xs:unique> </xs:element> 
like image 81
Michael Kay Avatar answered Oct 21 '22 13:10

Michael Kay