XmlChoiceIdentifierAttribute 类

定义

指定可以使用枚举进一步检测成员。

public ref class XmlChoiceIdentifierAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=false)]
public class XmlChoiceIdentifierAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue)]
public class XmlChoiceIdentifierAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue, AllowMultiple=false)>]
type XmlChoiceIdentifierAttribute = class
    inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Parameter | System.AttributeTargets.Property | System.AttributeTargets.ReturnValue)>]
type XmlChoiceIdentifierAttribute = class
    inherit Attribute
Public Class XmlChoiceIdentifierAttribute
Inherits Attribute
继承
XmlChoiceIdentifierAttribute
属性

示例

以下示例序列化一个名为 Choices 包含两个字段的类, MyChoice 以及 ManyChoices。 应用于 XmlChoiceIdentifierAttribute 每个字段,该字段指定通过 MemberName 属性 () 另一个类成员) 用于获取或设置检测成员值的枚举。 该 MyChoice 字段可以设置为单个值,并在字段中找到 EnumType 相应的枚举成员。 该 ManyChoices 字段返回对象的数组。 该 ChoiceArray 字段返回枚举值的数组。 对于字段中的每个数组成员 ManyChoices ,在字段返回 ChoiceArray 的数组中找到相应的成员。

#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 System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

public class Choices{
   // The MyChoice field can be set to any one of 
   // the types below. 
   [XmlChoiceIdentifier("EnumType")]
   [XmlElement("Word", typeof(string))]
   [XmlElement("Number", typeof(int))]
   [XmlElement("DecimalNumber", typeof(double))]
   public object MyChoice;

   // Don't serialize this field. The EnumType field
   // contains the enumeration value that corresponds
   // to the MyChoice field value.
   [XmlIgnore]
   public 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(int))]
   [XmlElement("Temp", typeof(double))]
   public object[] ManyChoices;

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

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

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

public class Test{
   static void Main(){
      Test t = new Test();
      t.SerializeObject("Choices.xml");
      t.DeserializeObject("Choices.xml");
   }

   private 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= "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",  5, 98.6};
      myChoices.ManyChoices=strChoices;

      // For each item in the ManyChoices array, add an
      // enumeration value.
      MoreChoices[] itmChoices = new MoreChoices[]
      {MoreChoices.Item, 
      MoreChoices.Amount,
      MoreChoices.Temp};
      myChoices.ChoiceArray=itmChoices;
      
      mySerializer.Serialize(writer, myChoices);
      writer.Close();
   }

   private 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 = (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.Length; i++){
      if(myChoices.ChoiceArray[i] == MoreChoices.Item)
        Console.WriteLine("Item: " + (string) 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: " + (string) myChoices.ManyChoices[i].ToString());
        }
   }
}
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

注解

命名 xsi:choice 的 XML 架构元素定义用于定义一个复杂元素,该元素只能包含实例中的一个子元素, (maxoccurs = 1) 。 该子级可以是多种类型之一,它可以具有多个名称之一。 每个名称都与特定类型相关联;但是,多个名称可以与同一类型相关联。 因此,此类元素的实例是模糊的。 例如,请考虑以下架构片段,该片段定义名为 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>  

使用该 XmlChoiceIdentifierAttribute 函数可将特殊枚举值分配给成员的每个实例。 必须自行创建枚举,也可以由 XML 架构定义工具 (Xsd.exe) 生成。 以下 C# 代码演示如何 XmlChoiceIdentifierAttribute 将字段应用于字段 Item ;该 MemberName 属性标识包含进一步用于检测选择的枚举的字段。

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,  
}  

此代码就位后,可以通过将 ItemType 字段设置为适当的枚举来序列化和反序列化此类。 例如,若要序列化 Choice 类,C# 代码如下所示。

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

反序列化时,C# 代码如下所示:

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);  
 }  

使用第二种方案时 XmlChoiceIdentifierAttribute 会出现这种情况。 在以下架构中,成员是返回 maxOccurs=“unbounded”) (的项数组的字段。 该数组可以包含第一个选项 (“D-a-t-a”) 的对象,以及第二个选项 (“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>  

然后,生成的类使用字段返回项数组。 对于数组中的每个项,还必须找到相应的 ItemChoiceType 枚举。 匹配的枚举包含在字段返回的 ItemsElementName 数组中。

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,  
}  

反序列化包含一系列选项的对象时,请使用控件结构 (,例如 if...然后。。。else 结构) 确定如何反序列化特定值。 在控件结构中,检查枚举值并相应地反序列化值。

构造函数

XmlChoiceIdentifierAttribute()

初始化 XmlChoiceIdentifierAttribute 类的新实例。

XmlChoiceIdentifierAttribute(String)

初始化 XmlChoiceIdentifierAttribute 类的新实例。

属性

MemberName

获取或设置字段的名称,该字段返回在检测类型时使用的枚举。

TypeId

在派生类中实现时,获取此 Attribute 的唯一标识符。

(继承自 Attribute)

方法

Equals(Object)

返回一个值,该值指示此实例是否与指定的对象相等。

(继承自 Attribute)
GetHashCode()

返回此实例的哈希代码。

(继承自 Attribute)
GetType()

获取当前实例的 Type

(继承自 Object)
IsDefaultAttribute()

在派生类中重写时,指示此实例的值是否是派生类的默认值。

(继承自 Attribute)
Match(Object)

当在派生类中重写时,返回一个指示此实例是否等于指定对象的值。

(继承自 Attribute)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
ToString()

返回表示当前对象的字符串。

(继承自 Object)

显式接口实现

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

将一组名称映射为对应的一组调度标识符。

(继承自 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。

(继承自 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。

(继承自 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对某一对象公开的属性和方法的访问。

(继承自 Attribute)

适用于

另请参阅