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 validate this against an XSD Schema, so that the combination between name
and color
are 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 will ignore object
elements without the optional color
attribute. The following validates correctly while it shouldn't.
<object name="ID2" />
<object name="ID2" />
Can you tell me how can I specify a rule that enforces unique name
and color
combinations and, when the color
attribute is not present in the element object
, it checks the name
?
You can create a Unique constraint within an XSD using the <xs:unique> element. The selector and field pair specify the data that must be unique, the XPath expressions are relative to the parent element (Directory).
Defining XML AttributesAttributes are either optional or mandatory (by default they are optional). The "use" property in the XSD definition is used to specify if the attribute is optional or mandatory.
Definition and Usage The complexType element defines a complex type. A complex type element is an XML element that contains other elements and/or attributes.
Use use
and default
with or without a value like:
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With