This documentation is archived and is not being maintained.

XmlChoiceIdentifierAttribute Class

Specifies that the member can be further detected by using an enumeration.


Namespace:  System.Xml.Serialization
Assembly:  System.Xml (in System.Xml.dll)

<AttributeUsageAttribute(AttributeTargets.Property Or AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.ReturnValue, AllowMultiple := False)> _
Public Class XmlChoiceIdentifierAttribute _
	Inherits Attribute

The XmlChoiceIdentifierAttribute type exposes the following members.

Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryXmlChoiceIdentifierAttributeInitializes a new instance of the XmlChoiceIdentifierAttribute class.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryXmlChoiceIdentifierAttribute(String)Initializes a new instance of the XmlChoiceIdentifierAttribute class.

Public propertySupported by the XNA FrameworkSupported by Portable Class LibraryMemberNameGets or sets the name of the field that returns the enumeration to use when detecting types.
Public propertyTypeIdWhen implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)

Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryEqualsInfrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetHashCodeReturns the hash code for this instance. (Inherited from Attribute.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodIsDefaultAttributeWhen overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)
Public methodSupported by the XNA FrameworkMatchWhen overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibraryMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibraryToStringReturns a string that represents the current object. (Inherited from Object.)

Explicit interface implemetationPrivate method_Attribute.GetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.GetTypeInfoRetrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.GetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.InvokeProvides access to properties and methods exposed by an object. (Inherited from Attribute.)

The XML schema element definition named xsi:choice is used to define a complex element that can contain only one child in an instance (maxoccurs = 1). That child can be one of several types, and it can have one of several names. Each name is associated with a specific type; however, several names can be associated with the same type. Because of this, an instance of such an element is indistinct. For example, consider the following schema fragment that defines such an indistinct element named MyChoice.

 <xsd:complexType name="MyChoice">
  <xsd:choice minOccurs="0" maxOccurs="1">
  <xsd:element minOccurs="1" maxOccurs="1" name="ChoiceOne" type="xsd:string" />
  <xsd:element minOccurs="1" maxOccurs="1" name="ChoiceTwo" type="xsd:string" />

The XmlChoiceIdentifierAttribute allows you to assign a special enumeration value to each instance of the member. You must either create the enumeration yourself or it can be generated by the XML Schema Definition Tool (Xsd.exe). The following C# code shows how the XmlChoiceIdentifierAttribute is applied to an Item field; the MemberName property identifies the field that contains the enumeration that is further used to detect the choice.

 public class Choices{
  public string MyChoice;

  // Do not serialize this next field:
  public ItemChoiceType ItemType;
 // Do not include this enumeration in the XML schema.
 [XmlType(IncludeInSchema = false)]
 public enum ItemChoiceType{

When this code is in place, you can serialize and deserialize this class by setting the ItemType field to an appropriate enumeration. For example, to serialize the Choice class, the C# code resembles the following.

 Choices mc = new Choices();
 mc.MyChoice = "Item Choice One";
 mc.ItemType = ItemChoiceType.ChoiceOne;

When deserializing, the C# code resembles the following:

 MyChoice mc = (MyChoice) myXmlSerializer.Deserialize(myReader);
 if(mc.ItemType == ItemChoiceType.ChoiceOne)
      // Handle choice one.
 if(mc.ItemType == ItemChoiceType.ChoiceTwo)
      // Handle choice two.
 if(mc.ItemType != null)
      throw CreateUnknownTypeException(mc.Item);

There is a second scenario when the XmlChoiceIdentifierAttribute is used. In the following schema, the member is a field that returns an array of items (maxOccurs="unbounded"). The array can contain objects of the first choice ("D-a-t-a"), and of the second choice ("MoreData").

 <xsd:complexType name="MyChoice">
  <xsd:choice minOccurs="0" maxOccurs="unbounded">
  <xsd:element minOccurs="1" maxOccurs="1" name="D-a-t-a" type="xsd:string" />
  <xsd:element minOccurs="1" maxOccurs="1" name="MoreData" type="xsd:string" />

The resulting class then uses a field to return an array of items. For each item in the array, a corresponding ItemChoiceType enumeration must also be found. The matching enumerations are contained in the array returned by the ItemsElementName field.

 public class MyChoice {
  [System.Xml.Serialization.XmlElementAttribute("D-a-t-a", typeof(string), IsNullable=false)]
  [System.Xml.Serialization.XmlElementAttribute("MoreData", typeof(string), IsNullable=false)]
  public string[] Items;
  public ItemsChoiceType[] ItemsElementName;
 public enum ItemsChoiceType {

When deserializing an object that includes a range of choices, use a control structure (such as an if...then...else structure) to determine how to deserialize a particular value. In the control structure, check the enumeration value and deserialize the value accordingly.

The following example serializes a class named Choices that includes two fields, MyChoice and ManyChoices. The XmlChoiceIdentifierAttribute is applied to each field that specifies (through the MemberName property) another class member that gets or sets an enumeration that detects the member value. The MyChoice field can be set to a single value, with a corresponding enumeration member found in the EnumType field. The ManyChoices field returns an array of objects. The ChoiceArray field returns an array of enumeration values. For each array member in the ManyChoices field, a corresponding member is found in the array returned by the ChoiceArray field.

Imports System
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO

Public Class Choices
   ' The MyChoice field can be set to any one of 
   ' the types below. 
   <XmlChoiceIdentifier("EnumType"), _
   XmlElement("Word", GetType(String)), _
   XmlElement("Number", GetType(Integer)), _
   XmlElement("DecimalNumber", GetType(double))> _
   Public MyChoice As Object 

   ' Don't serialize this field. The EnumType field
   ' contains the enumeration value that corresponds
   ' to the MyChoice field value.
   <XmlIgnore> _
   Public EnumType As ItemChoiceType 

   'The ManyChoices field can contain an array
   ' of choices. Each choice must be matched to
   ' an array item in the ChoiceArray field.
   <XmlChoiceIdentifier("ChoiceArray"), _
   XmlElement("Item", GetType(string)), _
   XmlElement("Amount", GetType(Integer)), _
   XmlElement("Temp", GetType(double))> _
   Public ManyChoices() As Object

   ' TheChoiceArray field contains the enumeration
   ' values, one for each item in the ManyChoices array.
   <XmlIgnore> _
   Public ChoiceArray() As MoreChoices
End Class

<XmlType(IncludeInSchema:=false)> _
Public Enum ItemChoiceType
End Enum

<XmlType(IncludeInSchema:=false)> _
Public Enum MoreChoices
End Enum

Public Class Test
   Shared Sub Main()
      Dim t  As Test = New Test()
   End Sub

   private Sub SerializeObject(filename As string)
      Dim mySerializer As XmlSerializer = _
      New XmlSerializer(GetType(Choices))
      Dim writer As TextWriter = New StreamWriter(filename)
      Dim myChoices As Choices = New Choices()

      ' Set the MyChoice field to a string. Set the
      ' EnumType to Word.
      myChoices.MyChoice= "Book"
      myChoices.EnumType = ItemChoiceType.Word

      ' Populate an object array with three items, one
      ' of each enumeration type. Set the array to the 
      ' ManyChoices field.
      Dim strChoices () As Object = New object(){"Food",  5, 98.6}

      ' For each item in the ManyChoices array, add an
      ' enumeration value.
      Dim itmChoices () As MoreChoices = New MoreChoices() _
      {MoreChoices.Item, _
      MoreChoices.Amount, _

      mySerializer.Serialize(writer, myChoices)
   End Sub

   private Sub DeserializeObject(filename As string)
      Dim ser As XmlSerializer = New XmlSerializer(GetType(Choices))

      ' A FileStream is needed to read the XML document.
      Dim fs As FileStream = New FileStream(filename, FileMode.Open)

      Dim myChoices As Choices = CType(ser.Deserialize(fs), Choices)


      ' Disambiguate the MyChoice value Imports the enumeration.
      if myChoices.EnumType = ItemChoiceType.Word Then
      	   Console.WriteLine("Word: " & _
      else if myChoices.EnumType = ItemChoiceType.Number Then 
      	   Console.WriteLine("Number: " & _
      else if myChoices.EnumType = ItemChoiceType.DecimalNumber Then
         Console.WriteLine("DecimalNumber: " & _
      	End If

      ' Disambiguate the ManyChoices values Imports the enumerations.
      Dim i As Integer
      for i = 0 to myChoices.ManyChoices.Length -1
      if myChoices.ChoiceArray(i) = MoreChoices.Item Then
      	Console.WriteLine("Item: " +  _
      else if myChoices.ChoiceArray(i) = MoreChoices.Amount Then
      	Console.WriteLine("Amount: " + _
      else if (myChoices.ChoiceArray(i) = MoreChoices.Temp)
      	Console.WriteLine("Temp: " + _
      	End If
      	Next i

   End Sub
End Class

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.