XmlChoiceIdentifierAttribute Class
Assembly: System.Xml (in system.xml.dll)
'Declaration <AttributeUsageAttribute(AttributeTargets.Property Or AttributeTargets.Field Or AttributeTargets.Parameter Or AttributeTargets.ReturnValue, AllowMultiple:=False)> _ Public Class XmlChoiceIdentifierAttribute Inherits Attribute 'Usage Dim instance As XmlChoiceIdentifierAttribute
/** @attribute AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue, AllowMultiple=false) */ public class XmlChoiceIdentifierAttribute extends Attribute
AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue, AllowMultiple=false) public class XmlChoiceIdentifierAttribute extends 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.
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 None Word Number DecimalNumber End Enum <XmlType(IncludeInSchema:=false)> _ Public Enum MoreChoices None Item Amount Temp End Enum Public Class Test Shared Sub Main() Dim t As Test = New Test() t.SerializeObject("Choices.xml") t.DeserializeObject("Choices.xml") 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} myChoices.ManyChoices=strChoices ' For each item in the ManyChoices array, add an ' enumeration value. Dim itmChoices () As MoreChoices = New MoreChoices() _ {MoreChoices.Item, _ MoreChoices.Amount, _ MoreChoices.Temp} myChoices.ChoiceArray=itmChoices mySerializer.Serialize(writer, myChoices) writer.Close() 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) fs.Close() ' Disambiguate the MyChoice value Imports the enumeration. if myChoices.EnumType = ItemChoiceType.Word Then Console.WriteLine("Word: " & _ myChoices.MyChoice.ToString()) else if myChoices.EnumType = ItemChoiceType.Number Then Console.WriteLine("Number: " & _ myChoices.MyChoice.ToString()) else if myChoices.EnumType = ItemChoiceType.DecimalNumber Then Console.WriteLine("DecimalNumber: " & _ myChoices.MyChoice.ToString()) 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: " + _ myChoices.ManyChoices(i).ToString()) else if myChoices.ChoiceArray(i) = MoreChoices.Amount Then Console.WriteLine("Amount: " + _ myChoices.ManyChoices(i).ToString()) else if (myChoices.ChoiceArray(i) = MoreChoices.Temp) Console.WriteLine("Temp: " + _ myChoices.ManyChoices(i).ToString()) End If Next i End Sub End Class
import System.*;
import System.Xml.*;
import System.Xml.Serialization.*;
import System.IO.*;
public class Choices
{
// The myChoice field can be set to any one of
// the types below.
/** @attribute XmlElement("word", String.class)
*/
/** @attribute XmlElement("Number", int.class)
*/
/** @attribute XmlElement("DecimalNumber", double.class)
*/
public Object myChoice;
// Don't serialize this field. The EnumType field
// contains the enumeration value that corresponds
// to the myChoice field value.
public int enumType;
// The manyChoices field can contain an array
// of choices. Each choice must be matched to
// an array item in the choiceArray field.
/** @attribute XmlElement("Item", String.class)
*/
/** @attribute XmlElement("amount", int.class)
*/
/** @attribute XmlElement("temp", double.class)
*/
public Object manyChoices[];
// ThechoiceArray field contains the enumeration
// values, one for each item in the manyChoices array.
public int choiceArray[];
} //Choices
/** @attribute XmlType(IncludeInSchema = false)
*/
public class ItemChoiceType
{
public static final int none = 0;
public static final int word = 1;
public static final int number = 2;
public static final int decimalNumber = 3;
} //ItemChoiceType
public class MoreChoices
{
public static final int none = 0;
public static final int item = 1;
public static final int amount = 2;
public static final int temp = 3;
} //MoreChoices
public class Test
{
public static void main(String[] args)
{
Test t = new Test();
t.SerializeObject("Choices.xml");
t.DeserializeObject("Choices.xml");
} //main
private void SerializeObject(String fileName)
{
XmlSerializer mySerializer = new XmlSerializer(Choices.class.ToType());
TextWriter writer = new StreamWriter(fileName);
Choices myChoices = 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.
Object strChoices[] = new Object[] { "Food", (Int32)5,
(System.Double)98.6 };
myChoices.manyChoices = strChoices;
// For each item in the manyChoices array, add an
// enumeration value.
int itmChoices[] = new int[] {
MoreChoices.item, MoreChoices.amount, MoreChoices.temp
};
myChoices.choiceArray = new int[itmChoices.get_Length()];
itmChoices.CopyTo(myChoices.choiceArray, 0);
//myChoices.choiceArray = itmChoices;
mySerializer.Serialize(writer, myChoices);
writer.Close();
} //SerializeObject
private void DeserializeObject(String fileName)
{
XmlSerializer ser = new XmlSerializer(Choices.class.ToType());
// A FileStream is needed to read the XML document.
FileStream fs = new FileStream(fileName, FileMode.Open);
Choices myChoices = (Choices)ser.Deserialize(fs);
fs.Close();
// Disambiguate the myChoice value using the enumeration.
if (myChoices.enumType == ItemChoiceType.word) {
Console.WriteLine("Word: " + myChoices.myChoice.ToString());
}
else {
if (myChoices.enumType == ItemChoiceType.number) {
Console.WriteLine("Number: " + myChoices.myChoice.ToString());
}
else {
if (myChoices.enumType == ItemChoiceType.decimalNumber) {
Console.WriteLine("DecimalNumber: " +
myChoices.myChoice.ToString());
}
}
}
// Disambiguate the manyChoices values using the enumerations.
for (int i = 0; i < myChoices.manyChoices.get_Length(); i++) {
if (System.Convert.ToInt32(myChoices.choiceArray.get_Item(i)) ==
MoreChoices.item) {
Console.WriteLine("Item: "
+ (String)(myChoices.manyChoices.get_Item(i)));
}
else {
if (System.Convert.ToInt32(myChoices.choiceArray.
get_Item(i)) == MoreChoices.amount) {
Console.WriteLine("Amount: " +
myChoices.manyChoices.get_Item(i).ToString());
}
}
if (System.Convert.ToInt32(myChoices.choiceArray.
get_Item(i)) == MoreChoices.temp) {
Console.WriteLine("Temp: " + (String)(
myChoices.manyChoices.get_Item(i).ToString()));
}
}
} //DeserializeObject
} //Test
Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.
Reference
XmlChoiceIdentifierAttribute MembersSystem.Xml.Serialization Namespace
XmlAttributes Class
Other Resources
Introducing XML SerializationHow to: Specify an Alternate Element Name for an XML Stream
Controlling XML Serialization Using Attributes
Examples of XML Serialization
XML Schema Definition Tool (Xsd.exe)