XmlChoiceIdentifierAttribute Osztály

Definíció

Megadja, hogy a tag enumerálással tovább észlelhető legyen.

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, AllowMultiple=false)>]
type XmlChoiceIdentifierAttribute = class
    inherit Attribute
Public Class XmlChoiceIdentifierAttribute
Inherits Attribute
Öröklődés
XmlChoiceIdentifierAttribute
Attribútumok

Példák

Az alábbi példa szerializál egy osztályt Choices , amely két mezőt MyChoice és ManyChoicesegy . A XmlChoiceIdentifierAttribute rendszer minden olyan mezőre alkalmazza, amely egy másik osztálytagot ad meg (a MemberName tulajdonságon keresztül), amely egy olyan enumerálást kap vagy állít be, amely észleli a tag értékét. A MyChoice mező beállítható egyetlen értékre, és a mezőben található egy megfelelő enumerálási EnumType tag. A ManyChoices mező objektumtömböt ad vissza. A ChoiceArray mező az enumerálási értékek tömbét adja vissza. A mező minden egyes tömbtagja ManyChoices esetében egy megfelelő tag található a mező által visszaadott ChoiceArray tömbben.

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

Megjegyzések

A névvel ellátott xsi:choice XML-sémaelem-definíció egy olyan összetett elem definiálására szolgál, amely egy példányban csak egy gyermeket tartalmazhat (maxoccurs = 1). Ez a gyermek több típus egyike lehet, és több név közül is választhat. Minden név egy adott típushoz van társítva; azonban több név is társítható ugyanahhoz a típushoz. Emiatt egy ilyen elem egy példánya nem felismerhetetlen. Vegyük például a következő sématöredéket, amely egy ilyen, ismeretlen MyChoicenevű elemet határoz meg.

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

Ez XmlChoiceIdentifierAttribute lehetővé teszi egy speciális számbavételi érték hozzárendelését a tag minden egyes példányához. Az enumerálást saját maga kell létrehoznia, vagy az XML-sémadefiníciós eszköz (Xsd.exe) hozhatja létre. Az alábbi C#-kód bemutatja, hogyan alkalmazza XmlChoiceIdentifierAttribute a rendszer a Item mezőt; a MemberName tulajdonság azonosítja azt a mezőt, amely a választás észleléséhez további enumerálást tartalmaz.

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

Ha ez a kód be van állítva, szerializálhatja és deszerializálhatja ezt az osztályt úgy, hogy a ItemType mezőt megfelelő számbavételre állítja. Az osztály szerializálásához Choice például a C# kód a következőhöz hasonló.

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

A deszerializáláskor a C#-kód a következőhöz hasonló:

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

A használatban van egy második forgatókönyv XmlChoiceIdentifierAttribute is. A következő sémában a tag egy olyan mező, amely egy elemtömböt ad vissza (maxOccurs="kötetlen"). A tömb tartalmazhat az elsőként választott objektumokat ("D-a-t-a"), a másodikat ("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>

Az eredményül kapott osztály ezután egy mezőt használ az elemek tömbjének visszaadásához. A tömb minden egyes eleméhez megfelelő ItemChoiceType enumerálást is meg kell találni. Az egyező enumerálásokat a mező által ItemsElementName visszaadott tömb tartalmazza.

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

Ha egy több választási lehetőséget tartalmazó objektumot deszerializál, használjon vezérlőstruktúrát (például ha... Akkor... más struktúra) egy adott érték deszerializálásának meghatározásához. A vezérlőszerkezetben ellenőrizze az enumerálási értéket, és ennek megfelelően deszerializálja az értéket.

Konstruktorok

Name Description
XmlChoiceIdentifierAttribute()

Inicializálja a XmlChoiceIdentifierAttribute osztály új példányát.

XmlChoiceIdentifierAttribute(String)

Inicializálja a XmlChoiceIdentifierAttribute osztály új példányát.

Tulajdonságok

Name Description
MemberName

Lekéri vagy beállítja annak a mezőnek a nevét, amely a típusok észlelésekor használandó számbavételt adja vissza.

TypeId

Ha származtatott osztályban implementálják, ehhez egy egyedi azonosítót Attributekap.

(Öröklődés forrása Attribute)

Metódusok

Name Description
Equals(Object)

Olyan értéket ad vissza, amely jelzi, hogy ez a példány egyenlő-e egy adott objektummal.

(Öröklődés forrása Attribute)
GetHashCode()

A példány kivonatkódját adja vissza.

(Öröklődés forrása Attribute)
GetType()

Lekéri az Type aktuális példányt.

(Öröklődés forrása Object)
IsDefaultAttribute()

Ha egy származtatott osztályban felül van bírálva, azt jelzi, hogy a példány értéke-e a származtatott osztály alapértelmezett értéke.

(Öröklődés forrása Attribute)
Match(Object)

Származtatott osztály felülírásakor egy olyan értéket ad vissza, amely jelzi, hogy ez a példány egy adott objektummal egyenlő-e.

(Öröklődés forrása Attribute)
MemberwiseClone()

Az aktuális Objectpéldány sekély másolatát hozza létre.

(Öröklődés forrása Object)
ToString()

Az aktuális objektumot jelképező sztringet ad vissza.

(Öröklődés forrása Object)

Explicit interfész-implementációk

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

Névkészletet képez le a küldési azonosítók megfelelő készletére.

(Öröklődés forrása Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Lekéri egy objektum típusadatait, amelyek a felület típusadatainak lekérésére használhatók.

(Öröklődés forrása Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Lekéri az objektumok által biztosított típusinformációs felületek számát (0 vagy 1).

(Öröklődés forrása Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Hozzáférést biztosít az objektumok által közzétett tulajdonságokhoz és metódusokhoz.

(Öröklődés forrása Attribute)

A következőre érvényes:

Lásd még