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
属性

次の例では、 MyChoice ManyChoices2 つのフィールドと Choices . これは XmlChoiceIdentifierAttribute 、メンバー値を検出する列挙体を取得または設定する別のクラス メンバーを MemberName (プロパティを介して) 指定する各フィールドに適用されます。 フィールドは MyChoice 1 つの値に設定でき、フィールドに対応する列挙メンバーが 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 スキーマ要素定義は、インスタンス内に 1 つの子のみを含めることができる複合要素を定義するために使用されます (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# コードは、フィールドMemberNameへの適用方法XmlChoiceIdentifierAttributeItem示しています。プロパティは、選択を検出するためにさらに使用される列挙体を含むフィールドを識別します。

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

使用される 2 番目の XmlChoiceIdentifierAttribute シナリオがあります。 次のスキーマでは、メンバーは項目の配列 (maxOccurs="unbounded") を返すフィールドです。 配列には、最初の選択肢 ("D-a-t-a")、2 番目の選択肢 ("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)

適用対象

こちらもご覧ください