69

I'm stuck trying to define an XSD containing a field that can have only one of the following three values:

  • Green
  • Red
  • Blue

Essentially, I want to define a strict enumeration at the Schema level.

My First attempt appears wrong and I'm not sure about the "right" way to fix it.

<xs:element name="color">
    <xs:complexType>
        <xs:choice>
            <xs:element name="green"/>
            <xs:element name="red"/>
            <xs:element name="blue"/>
        </xs:choice>
    </xs:complexType>
</xs:element>

By using an automatic XML generator, it treats those element names as string objects:

<xs0:color>
    <xs0:green>text</xs0:green>
</xs0:color>
kjhughes
  • 106,133
  • 27
  • 181
  • 240
Nate
  • 18,892
  • 27
  • 70
  • 93

2 Answers2

116

You can define an enumeration within the context of a simpleType.

 <xs:simpleType name="color" final="restriction" >
    <xs:restriction base="xs:string">
        <xs:enumeration value="green" />
        <xs:enumeration value="red" />
        <xs:enumeration value="blue" />
    </xs:restriction>
</xs:simpleType>
<xs:element name="SomeElement">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="Color" type="color" />
        </xs:sequence>
    </xs:complexType>
</xs:element>
Colin Cochrane
  • 2,565
  • 1
  • 19
  • 20
  • 7
    I would recommend using an extension of NMTOKEN, though, rather than String. It's more consist with the idea of an enum, I think. It's also more tool-friendly, particularly with code generators. – skaffman Aug 07 '09 at 08:55
5

This solution worked for me:

<xs:element name="color">
   <xs:simpleType>
      <xs:restriction base="xs:string">
          <xs:enumeration value="green"/>
          <xs:enumeration value="red"/>
          <xs:enumeration value="blue"/>
      </xs:restriction>
   </xs:simpleType>
</xs:element>
salerokada
  • 334
  • 3
  • 7