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)

將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。

(繼承來源 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

擷取物件的類型資訊,可以用來取得介面的類型資訊。

(繼承來源 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

擷取物件提供的類型資訊介面數目 (0 或 1)。

(繼承來源 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供物件所公開的屬性和方法的存取權。

(繼承來源 Attribute)

適用於

另請參閱