views:

237

answers:

2

We have a lot of serialization done through MS XML 4. When we serialize C++ enums we use a table to translate each possible value to a string and them store that string as an attribute value. When we deserialize we read that attribute value, compare it against all items in the table and retrieve the corresponding enum value. If we fail to find we raise an error.

To facilitate creating XMLs by external programs we published XML schemas for all data types of interest. Attributes for enums are defined as follows:

<xs:complexType>
    //other fields here
    <xs:attribute name="Color" type="xs:string"></xs:attribute>
</xs:complexType>

It works, but contains no definitions for what are possible string values. How could I add possible values to this definition? Do I use xs:choice for that?

A: 
<xs:complexType>
  //other fields here
  <xs:attribute name="Color">
    <xs:simpleType>
      <xs:restriction base="xs:string">
        <xs:enumeration value="RED"/>
        <xs:enumeration value="BLUE"/>
        <xs:enumeration value="GREEN"/>
      </xs:restriction>
    </xs:simpleType>
  </xs:attribute>
</xs:complexType>

You can also create that as an external type:

<xs:complexType>
  //other fields here
  <xs:attribute name="Color" type="Color"/>
</xs:complexType>
<xs:simpleType name="Color">
  <xs:restriction base="xs:string">
    <xs:enumeration value="RED"/>
    <xs:enumeration value="BLUE"/>
    <xs:enumeration value="GREEN"/>
  </xs:restriction>
</xs:simpleType>

<xs:choice> means something else entirely. The names in XML schema are unintuitive and somewhat misleading. Choice means one of the contained elements.

cletus
in practice though (while I agree with you) don't they accomplish essentially the same thing?
Nona Urbiz
+2  A: 

No, xs:choice provides the schema with information that says "in this spot, you can have this or this or this, but not a combination"; you can find out more about xs:choice here.

To create an enumeration you need to define them as part of a restricted type based on xs:string.

For example:

<xs:simpleType name="ColorType">
  <xs:restriction base="xs:string">
    <xs:enumeration value="white"/>
    <xs:enumeration value="black"/>
    <xs:enumeration value="blue"/>
  </xs:restriction>
</xs:simpleType>

You can then use this type like any other:

<xs:complexType>
  <xs:attribute name="Color" type="ColorType" />
</xs:complexType>

For more information on using xs:restriction and other XSD elements and attributes, check out www.w3schools.com. They have good reference guides and tutorials on many topics related to the web such as XHTML, XSLT, XPath, and XSD (as well as javascript and AJAX).

Jeff Yates