Xsd: unique with optional attributes

I have this xml file:

<objects> <object name="ID1" /> <object name="ID2" /> <object name="ID2" color="green" /> <object name="ID3" color="green" /> <objects> 

I would like to test this on the XSD schema, so the combination between name and color unique in the document.

The problem is that if I use:

 <xs:unique name="UniqueObjectNameColor"> <xs:selector xpath="./object" /> <xs:field xpath="@name" /> <xs:field xpath="@color" /> </xs:unique> 

... the rule ignores object elements without the additional color attribute. The following correct statement is correct, while it should not.

  <object name="ID2" /> <object name="ID2" /> 

Can you tell me how to specify a rule that applies unique combinations of name and color , and when the color attribute is missing from the object element, it checks the name ?

+6
xml unique xsd
source share
2 answers

Use use and default with or without a value, for example:

  <element name="objects"> <complexType> <sequence> <element name="object" maxOccurs="unbounded"> <complexType> <attribute name="name" type="string" /> <attribute name="color" type="string" use="optional" default="noColor" /> </complexType> </element> </sequence> </complexType> <unique name="UniqueObjectNameColor"> <selector xpath="tns:object" /> <field xpath="@name" /> <field xpath="@color" /> </unique> </element> </schema> 
+4
source share

Old question, but worth the answer. You can use more than one unique constraint for each element. This will do what you want:

 <?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/xsdunique-with-optional-properties" xmlns:tns="http://www.example.org/xsdunique-with-optional-properties" elementFormDefault="qualified" attributeFormDefault="unqualified"> <element name="objects"> <complexType> <sequence> <element name="object" maxOccurs="unbounded"> <complexType> <attribute name="name" type="string" /> <attribute name="color" type="string" /> </complexType> </element> </sequence> </complexType> <unique name="UniqueObjectName"> <selector xpath="tns:object" /> <field xpath="@name" /> </unique> <unique name="UniqueObjectNameColor"> <selector xpath="tns:object" /> <field xpath="@name" /> <field xpath="@color" /> </unique> </element> </schema> 
0
source share

All Articles