69

Is there a way to specify that one of 2 attributes is required in XSD?

for example, I have a definition like this:

<xs:attribute name="Name" type="xs:string" use="optional" />
<xs:attribute name="Id" type="xs:string" use="optional" />

I want to be able to define that at least one of these is required. Is that possible?

Jens
  • 8,423
  • 9
  • 58
  • 78
user92454
  • 1,201
  • 1
  • 10
  • 13

5 Answers5

47

No, I don't think you can do that with attributes. You could wrap two <xs:element> into a <xs:choice> - but for attributes, there's no equivalent construct, I'm afraid.

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • This doesn't work with mutliple elements with the same name... i.e. I want three possible combinations of an element of a certain name, and making a choice of the three complex types with the same names fails :( – Rimer Aug 02 '18 at 20:57
30

XSD 1.1 will let you do this using asserts.

<xsd:element name="remove">
    <xsd:complexType>                        
        <xsd:attribute name="ref" use="optional"/>
        <xsd:attribute name="uri" use="optional"/>
        <xsd:assert test="(@ref and not(@uri)) or (not(@ref) and @uri)"/>            
    </xsd:complexType>
</xsd:element>
jeremiah jahn
  • 311
  • 3
  • 3
  • 1
    Nice solution, but since it was released in 2012 (http://www.w3.org/TR/xmlschema11-1/) , and I'm using .NET 4.0, (released in 2010) it's not supported. Is it supported in .NET 4.5? Example class: https://msdn.microsoft.com/en-us/library/swxzdhc0(v=vs.110).aspx – Denise Skidmore Oct 08 '15 at 16:37
  • Cannot we do something like `` ? – Jawaid Jun 17 '20 at 15:30
  • 4
    I don't believe that the xsl 'or' is exclusive. We want it to be one or the other, but not both. – jeremiah jahn Jun 18 '20 at 16:14
9

Marc is quite right... You cannot have xs:attribute child elements inside a xs:choice parent element in XSD.

The logic seems to be that if two instances of an element have a mutually exclusive set of attributes then they are logically two different elements.

A workaround for this has been presented by Jeni Tennison here.

Cerebrus
  • 25,615
  • 8
  • 56
  • 70
5

You should look at this pages on W3C wiki: Simple attribute implication and Attribute muttex

Ondřej Doněk
  • 529
  • 1
  • 10
  • 17
-3

The example defines an element named "person" which must contain either a "employee" element or a "member" element.

<xs:element name="person">
  <xs:complexType>
    <xs:choice>
      <xs:element name="employee" type="employee"/>
      <xs:element name="member" type="member"/>
    </xs:choice>
  </xs:complexType>
</xs:element>
NIthin
  • 3
  • 1