Export (0) Print
Expand All

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|AttributeTargets::Field|AttributeTargets::Parameter|AttributeTargets::ReturnValue, AllowMultiple = false)]
public ref class XmlChoiceIdentifierAttribute : public 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:sequence>
  <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" />
  </xsd:choice>
  </xsd:sequence>
 </xsd:complexType>

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{
  [XmlChoiceIdentifier("ItemType")]
  [XmlChoiceIdentifier("ChoiceOne")]
  [XmlChoiceIdentifier("ChoiceTwo")]
  public string MyChoice;

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

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:sequence>
  <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" />
  </xsd:choice>
  </xsd:sequence>
 </xsd:complexType>

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)]
  [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")]
  public string[] Items;
  [System.Xml.Serialization.XmlElementAttribute(IsNullable=false)]
  [System.Xml.Serialization.XmlIgnoreAttribute()]
  public ItemsChoiceType[] ItemsElementName;
 }
 [System.Xml.Serialization.XmlTypeAttribute(IncludeInSchema=false)]
 public enum ItemsChoiceType {
  [System.Xml.Serialization.XmlEnumAttribute("D-a-t-a")]
  Data,
  MoreData,
 }

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.

#using <System.dll>
#using <System.xml.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Serialization;
using namespace System::IO;

[XmlType(IncludeInSchema=false)]

public enum class ItemChoiceType
{
   None, Word, Number, DecimalNumber
};

public enum class MoreChoices
{
   None, Item, Amount, Temp
};

public ref class Choices
{
public:

   // The MyChoice field can be set to any one of  
   // the types below. 

   [XmlChoiceIdentifier("EnumType")]
   [XmlElement("Word",String::typeid)]
   [XmlElement("Number",Int32::typeid)]
   [XmlElement("DecimalNumber",Double::typeid)]
   Object^ MyChoice;

   // Don't serialize this field. The EnumType field 
   // contains the enumeration value that corresponds 
   // to the MyChoice field value.

   [XmlIgnore]
   ItemChoiceType EnumType;

   // 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",String::typeid)]
   [XmlElement("Amount",Int32::typeid)]
   [XmlElement("Temp",Double::typeid)]
   array<Object^>^ManyChoices;

   // TheChoiceArray field contains the enumeration 
   // values, one for each item in the ManyChoices array.

   [XmlIgnore]
   array<MoreChoices>^ChoiceArray;
};

void SerializeObject( String^ filename );
void DeserializeObject( String^ filename );
int main()
{
   SerializeObject( "Choices.xml" );
   DeserializeObject( "Choices.xml" );
}

void SerializeObject( String^ filename )
{
   XmlSerializer^ mySerializer = gcnew XmlSerializer( Choices::typeid );
   TextWriter^ writer = gcnew StreamWriter( filename );
   Choices^ myChoices = gcnew 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. 
   array<Object^>^strChoices = {"Food",5,98.6};
   myChoices->ManyChoices = strChoices;

   // For each item in the ManyChoices array, add an 
   // enumeration value. 
   array<MoreChoices>^ itmChoices = {MoreChoices::Item,MoreChoices::Amount,MoreChoices::Temp};
   myChoices->ChoiceArray = itmChoices;
   mySerializer->Serialize( writer, myChoices );
   writer->Close();
}

void DeserializeObject( String^ filename )
{
   XmlSerializer^ ser = gcnew XmlSerializer( Choices::typeid );

   // A FileStream is needed to read the XML document.
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   Choices^ myChoices = safe_cast<Choices^>(ser->Deserialize( fs ));
   fs->Close();

   // Disambiguate the MyChoice value using the enumeration. 
   if ( myChoices->EnumType == ItemChoiceType::Word )
   {
      Console::WriteLine( "Word: {0}", myChoices->MyChoice->ToString() );
   }
   else 
   if ( myChoices->EnumType == ItemChoiceType::Number )
   {
      Console::WriteLine( "Number: {0}", myChoices->MyChoice->ToString() );
   }
   else 
   if ( myChoices->EnumType == ItemChoiceType::DecimalNumber )
   {
      Console::WriteLine( "DecimalNumber: {0}", myChoices->MyChoice->ToString() );
   }

   // Disambiguate the ManyChoices values using the enumerations. 
   for ( int i = 0; i < myChoices->ManyChoices->Length; i++ )
   {
      if ( myChoices->ChoiceArray[ i ] == MoreChoices::Item )
            Console::WriteLine( "Item: {0}", myChoices->ManyChoices[ i ] );
      else 
      if ( myChoices->ChoiceArray[ i ] == MoreChoices::Amount )
            Console::WriteLine( "Amount: ", myChoices->ManyChoices[ i ]->ToString() );
      if ( myChoices->ChoiceArray[ i ] == MoreChoices::Temp )
            Console::WriteLine( "Temp: {0}", myChoices->ManyChoices[ i ]->ToString() );
   }
}
#using <mscorlib.dll>
#using <System.dll>
#using <System.xml.dll>

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Serialization;
using namespace System::IO;

[XmlType(IncludeInSchema=false)]
public __value enum ItemChoiceType
{
   None,
   Word, 
   Number,
   DecimalNumber
};

public __value enum MoreChoices
{
   None,
   Item,
   Amount,
   Temp
};

public __gc class Choices
{
public:
   // The MyChoice field can be set to any one of 
   // the types below. 
   [XmlChoiceIdentifier("EnumType")]
   [XmlElement("Word", __typeof(String))]
   [XmlElement("Number", __typeof(Int32))]
   [XmlElement("DecimalNumber", __typeof(Double))]
   Object*	MyChoice;

   // Don't serialize this field. The EnumType field
   // contains the enumeration value that corresponds
   // to the MyChoice field value.
   [XmlIgnore]
   ItemChoiceType EnumType;

   // 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", __typeof(String))]
   [XmlElement("Amount", __typeof(Int32))]
   [XmlElement("Temp", __typeof(Double))]
   Object*	ManyChoices[];

   // TheChoiceArray field contains the enumeration
   // values, one for each item in the ManyChoices array.
   [XmlIgnore]
   MoreChoices	ChoiceArray[];
};

void SerializeObject(String* filename);
void DeserializeObject(String* filename);

int main(){
   SerializeObject(S"Choices.xml");
   DeserializeObject(S"Choices.xml");
}

void SerializeObject(String* filename)
{
   XmlSerializer* mySerializer = 
      new XmlSerializer(__typeof(Choices));
   TextWriter* writer = new StreamWriter(filename);
   Choices* myChoices = new Choices();

   // Set the MyChoice field to a string. Set the
   // EnumType to Word.
   myChoices->MyChoice= S"Book";
   myChoices->EnumType = ItemChoiceType::Word;

   // Populate an object array with three items, one
   // of each enumeration type. Set the array to the 
   // ManyChoices field.
   Object*	strChoices[] = {S"Food", __box(5), __box(98.6) };
   myChoices->ManyChoices = strChoices;

   // For each item in the ManyChoices array, add an
   // enumeration value.
   MoreChoices	itmChoices[] =
   {MoreChoices::Item, 
   MoreChoices::Amount,
   MoreChoices::Temp};
   myChoices->ChoiceArray = itmChoices;

   mySerializer->Serialize(writer, myChoices);
   writer->Close();
}

void DeserializeObject(String* filename){
   XmlSerializer* ser = new XmlSerializer(__typeof(Choices));

   // A FileStream is needed to read the XML document.
   FileStream* fs = new FileStream(filename, FileMode::Open);
   Choices* myChoices = __try_cast<Choices*>( ser->Deserialize(fs));
   fs->Close();

   // Disambiguate the MyChoice value using the enumeration.
   if(myChoices->EnumType == ItemChoiceType::Word)
   {
      Console::WriteLine( S"Word: {0}", myChoices->MyChoice->ToString());
   }
   else if( myChoices->EnumType == ItemChoiceType::Number)
   {
      Console::WriteLine( S"Number: {0}", myChoices->MyChoice->ToString());
   }
   else if( myChoices->EnumType == ItemChoiceType::DecimalNumber)
   {
      Console::WriteLine( S"DecimalNumber: {0}", myChoices->MyChoice->ToString());
   }

   // Disambiguate the ManyChoices values using the enumerations.
   for( int i = 0; i<myChoices->ManyChoices->Length; i++)
   {
      if ( myChoices->ChoiceArray[i] == MoreChoices::Item)
         Console::WriteLine( S"Item: {0}", myChoices->ManyChoices[i]);	
      else if ( myChoices->ChoiceArray[i] == MoreChoices::Amount )
         Console::WriteLine( S"Amount: ", myChoices->ManyChoices[i]->ToString());
      if(myChoices->ChoiceArray[i] == MoreChoices::Temp)
         Console::WriteLine(S"Temp: {0}" , myChoices->ManyChoices[i]->ToString());
   }

}

System::Object
  System::Attribute
    System.Xml.Serialization::XmlChoiceIdentifierAttribute

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

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

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

.NET Framework

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

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

XNA Framework

Supported in: 3.0, 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft