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 를 직렬화합니다ManyChoices. MyChoice 속성 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# 코드는 필드에 MemberName 적용되는 Item 방법을 XmlChoiceIdentifierAttribute 보여 줍니다. 속성은 선택 항목을 검색하는 데 추가로 사용되는 열거형이 포함된 필드를 식별합니다.

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 structure) - 특정 값을 역직렬화하는 방법을 결정합니다. 컨트롤 구조에서 열거형 값을 확인하고 그에 따라 값을 역직렬화합니다.

생성자

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)

적용 대상

추가 정보