Search code examples
xmlxsdxsd-1.0

XSD - unique values of two different attributes


It is possible at schema level to enforce unique values of two attributes with different name?

<xs:complexType name="exampleType">
  <xs:attribute name="first" type="xs:integer" use="required"/>
  <xs:attribute name="second" type="xs:integer"/>
</xs:complexType>

If first is 1, second needs to be some other value.

EDIT: I am using xsd 1.0.


Solution

  • As I said in my comment this is only valid if first and second are elements (not attributes). The | xpath operator it's like a union of nodes.

    <xs:element name="exampleElement" type="exampleType">
        <xs:unique name="firstAndSecondDifferent">
            <xs:selector xpath="first | second" />
            <xs:field xpath="." />
        </xs:unique>
    </xs:element>
    
    <xs:complexType name="exampleType">
        <xs:sequence>
            <xs:element name="first" type="xs:integer" />
            <xs:element name="second" type="xs:integer" minOccurs="0" />
        </xs:sequence>
    </xs:complexType>
    

    The following element is valid (first and second have different values):

    <exampleElement>
        <first>1</first>
        <second>5</second>
    </exampleElement>
    

    The following element is valid (no second element present):

    <exampleElement>
        <first>1</first>
    </exampleElement>
    

    The following element is not valid (first and second have the same value):

    <exampleElement>
        <first>1</first>
        <second>1</second>
    </exampleElement>
    

    This can't be done with attributes because selector xpath doesn't allow to use attributes so "@first | @second" it's not a valid value of the xpath attribute of a selector.