XmlChoiceIdentifierAttribute Klas

Definitie

Hiermee geeft u op dat het lid verder kan worden gedetecteerd met behulp van een opsomming.

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
Overname
XmlChoiceIdentifierAttribute
Kenmerken

Voorbeelden

In het volgende voorbeeld wordt een klasse geserialiseerd Choices die twee velden bevat en MyChoiceManyChoices. De XmlChoiceIdentifierAttribute waarde wordt toegepast op elk veld dat een ander klasselid opgeeft (via de MemberName eigenschap) dat een opsomming ophaalt of instelt waarmee de lidwaarde wordt gedetecteerd. Het MyChoice veld kan worden ingesteld op één waarde, met een bijbehorend opsommingslid in het EnumType veld. Het ManyChoices veld retourneert een matrix met objecten. Het ChoiceArray veld retourneert een matrix met opsommingswaarden. Voor elk matrixlid in het ManyChoices veld wordt een corresponderend lid gevonden in de matrix die door het ChoiceArray veld wordt geretourneerd.

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

Opmerkingen

De definitie van het XML-schema-element met de naam xsi:choice wordt gebruikt om een complex element te definiëren dat slechts één onderliggend element in een exemplaar mag bevatten (maxoccurs = 1). Dat kind kan een van de verschillende typen zijn en kan een van de namen hebben. Elke naam is gekoppeld aan een specifiek type; er kunnen echter verschillende namen aan hetzelfde type worden gekoppeld. Daarom is een exemplaar van een dergelijk element niet van belang. Denk bijvoorbeeld aan het volgende schemafragment dat een dergelijk niet-gedefinieerd element met de naam MyChoicedefinieert.

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

Hiermee XmlChoiceIdentifierAttribute kunt u een speciale opsommingswaarde toewijzen aan elk exemplaar van het lid. U moet zelf de opsomming maken of deze kan worden gegenereerd door het XML Schema Definition Tool (Xsd.exe).< De volgende C#-code laat zien hoe de XmlChoiceIdentifierAttribute code wordt toegepast op een Item veld. De MemberName eigenschap identificeert het veld dat de opsomming bevat die verder wordt gebruikt om de keuze te detecteren.

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

Wanneer deze code is ingesteld, kunt u deze klasse serialiseren en deserialiseren door het ItemType veld in te stellen op een geschikte opsomming. Als u bijvoorbeeld de Choice klasse wilt serialiseren, lijkt de C#-code op het volgende.

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

Bij het deserialiseren lijkt de C#-code op het volgende:

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

Er is een tweede scenario wanneer het XmlChoiceIdentifierAttribute wordt gebruikt. In het volgende schema is het lid een veld dat een matrix met items retourneert (maxOccurs="unbounded"). De matrix kan objecten van de eerste keuze ('D-a-t-a') en van de tweede keuze ('MoreData') bevatten.

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

De resulterende klasse gebruikt vervolgens een veld om een matrix met items te retourneren. Voor elk item in de matrix moet ook een bijbehorende ItemChoiceType opsomming worden gevonden. De overeenkomende opsommingen zijn opgenomen in de matrix die door het ItemsElementName veld wordt geretourneerd.

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

Wanneer u een object met een bereik van keuzen deserialiseerd, gebruikt u een besturingsstructuur (zoals een if... Dan... else structure) om te bepalen hoe een bepaalde waarde moet worden gedeserialiseerd. Controleer in de besturingsstructuur de opsommingswaarde en deserialiseer de waarde dienovereenkomstig.

Constructors

Name Description
XmlChoiceIdentifierAttribute()

Initialiseert een nieuw exemplaar van de XmlChoiceIdentifierAttribute klasse.

XmlChoiceIdentifierAttribute(String)

Initialiseert een nieuw exemplaar van de XmlChoiceIdentifierAttribute klasse.

Eigenschappen

Name Description
MemberName

Hiermee haalt u de naam op van het veld dat de opsomming retourneert die moet worden gebruikt bij het detecteren van typen.

TypeId

Wanneer deze wordt geïmplementeerd in een afgeleide klasse, krijgt u Attributehiervoor een unieke id.

(Overgenomen van Attribute)

Methoden

Name Description
Equals(Object)

Retourneert een waarde die aangeeft of dit exemplaar gelijk is aan een opgegeven object.

(Overgenomen van Attribute)
GetHashCode()

Retourneert de hash-code voor dit exemplaar.

(Overgenomen van Attribute)
GetType()

Hiermee haalt u de Type huidige instantie op.

(Overgenomen van Object)
IsDefaultAttribute()

Wanneer deze wordt overschreven in een afgeleide klasse, geeft u aan of de waarde van dit exemplaar de standaardwaarde is voor de afgeleide klasse.

(Overgenomen van Attribute)
Match(Object)

Wanneer deze wordt overschreven in een afgeleide klasse, wordt een waarde geretourneerd die aangeeft of dit exemplaar gelijk is aan een opgegeven object.

(Overgenomen van Attribute)
MemberwiseClone()

Hiermee maakt u een ondiepe kopie van de huidige Object.

(Overgenomen van Object)
ToString()

Retourneert een tekenreeks die het huidige object vertegenwoordigt.

(Overgenomen van Object)

Expliciete interface-implementaties

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

Hiermee wordt een set namen toegewezen aan een bijbehorende set verzend-id's.

(Overgenomen van Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Hiermee haalt u de typegegevens voor een object op, die kan worden gebruikt om de typegegevens voor een interface op te halen.

(Overgenomen van Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Hiermee wordt het aantal type-informatieinterfaces opgehaald dat een object biedt (0 of 1).

(Overgenomen van Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Biedt toegang tot eigenschappen en methoden die door een object worden weergegeven.

(Overgenomen van Attribute)

Van toepassing op

Zie ook