Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xsd:unique with optional attributes

Tags:

xml

unique

xsd

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?

like image 807
Vitor Avatar asked Dec 01 '10 11:12

Vitor


People also ask

How do you make an attribute unique in XSD?

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).

Are XML attributes optional?

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.

What does complexType mean in XSD?

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.


1 Answers

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>
like image 128
Jan Hueter Avatar answered Oct 14 '22 06:10

Jan Hueter