XmlAttributeOverrides Klasa

Definicja

Umożliwia zastąpienie właściwości, pola i atrybutów klasy podczas używania XmlSerializer elementu do serializacji lub deserializacji obiektu.

public ref class XmlAttributeOverrides
public class XmlAttributeOverrides
type XmlAttributeOverrides = class
Public Class XmlAttributeOverrides
Dziedziczenie
XmlAttributeOverrides

Przykłady

Poniższy przykład serializuje klasę o nazwie , która zawiera jedno pole o nazwie Orchestra``Instruments , które zwraca tablicę Instrument obiektów. Druga klasa o nazwie Brass dziedziczy z Instrument klasy. W przykładzie użyto wystąpienia XmlAttributeOverrides klasy w celu zastąpienia Instrument pola, co pozwala na akceptowanie Brass obiektów przez pole.

#using <System.Xml.dll>
#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml::Serialization;

public ref class Instrument
{
public:
   String^ Name;
};

public ref class Brass: public Instrument
{
public:
   bool IsValved;
};

public ref class Orchestra
{
public:
   array<Instrument^>^Instruments;
};

void SerializeObject( String^ filename )
{
   /* Each overridden field, property, or type requires 
      an XmlAttributes object. */
   XmlAttributes^ attrs = gcnew XmlAttributes;

   /* Create an XmlElementAttribute to override the 
      field that returns Instrument objects. The overridden field
      returns Brass objects instead. */
   XmlElementAttribute^ attr = gcnew XmlElementAttribute;
   attr->ElementName = "Brass";
   attr->Type = Brass::typeid;

   // Add the element to the collection of elements.
   attrs->XmlElements->Add( attr );

   // Create the XmlAttributeOverrides object.
   XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;

   /* Add the type of the class that contains the overridden 
      member and the XmlAttributes to override it with to the 
      XmlAttributeOverrides object. */
   attrOverrides->Add( Orchestra::typeid, "Instruments", attrs );

   // Create the XmlSerializer using the XmlAttributeOverrides.
   XmlSerializer^ s = gcnew XmlSerializer( Orchestra::typeid,attrOverrides );

   // Writing the file requires a TextWriter.
   TextWriter^ writer = gcnew StreamWriter( filename );

   // Create the object that will be serialized.
   Orchestra^ band = gcnew Orchestra;

   // Create an object of the derived type.
   Brass^ i = gcnew Brass;
   i->Name = "Trumpet";
   i->IsValved = true;
   array<Instrument^>^myInstruments = {i};
   band->Instruments = myInstruments;

   // Serialize the object.
   s->Serialize( writer, band );
   writer->Close();
}

void DeserializeObject( String^ filename )
{
   XmlAttributeOverrides^ attrOverrides = gcnew XmlAttributeOverrides;
   XmlAttributes^ attrs = gcnew XmlAttributes;

   // Create an XmlElementAttribute to override the Instrument.
   XmlElementAttribute^ attr = gcnew XmlElementAttribute;
   attr->ElementName = "Brass";
   attr->Type = Brass::typeid;

   // Add the XmlElementAttribute to the collection of objects.
   attrs->XmlElements->Add( attr );
   attrOverrides->Add( Orchestra::typeid, "Instruments", attrs );

   // Create the XmlSerializer using the XmlAttributeOverrides.
   XmlSerializer^ s = gcnew XmlSerializer( Orchestra::typeid,attrOverrides );
   FileStream^ fs = gcnew FileStream( filename,FileMode::Open );
   Orchestra^ band = dynamic_cast<Orchestra^>(s->Deserialize( fs ));
   Console::WriteLine( "Brass:" );

   /* The difference between deserializing the overridden 
      XML document and serializing it is this: To read the derived 
      object values, you must declare an object of the derived type 
      (Brass), and cast the Instrument instance to it. */
   Brass^ b;
   System::Collections::IEnumerator^ myEnum = band->Instruments->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Instrument^ i = safe_cast<Instrument^>(myEnum->Current);
      b = dynamic_cast<Brass^>(i);
      Console::WriteLine( "{0}\n{1}", b->Name, b->IsValved );
   }
}

int main()
{
   SerializeObject( "Override.xml" );
   DeserializeObject( "Override.xml" );
}
using System;
using System.IO;
using System.Xml.Serialization;

public class Orchestra
{
   public Instrument[] Instruments;
}

public class Instrument
{
   public string Name;
}

public class Brass:Instrument
{
   public bool IsValved;
}

public class Run
{
    public static void Main()
    {
       Run test = new Run();
       test.SerializeObject("Override.xml");
       test.DeserializeObject("Override.xml");
    }

    public void SerializeObject(string filename)
    {
      /* Each overridden field, property, or type requires
      an XmlAttributes object. */
      XmlAttributes attrs = new XmlAttributes();

      /* Create an XmlElementAttribute to override the
      field that returns Instrument objects. The overridden field
      returns Brass objects instead. */
      XmlElementAttribute attr = new XmlElementAttribute();
      attr.ElementName = "Brass";
      attr.Type = typeof(Brass);

      // Add the element to the collection of elements.
      attrs.XmlElements.Add(attr);

      // Create the XmlAttributeOverrides object.
      XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();

      /* Add the type of the class that contains the overridden
      member and the XmlAttributes to override it with to the
      XmlAttributeOverrides object. */
      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Create the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s =
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      // Writing the file requires a TextWriter.
      TextWriter writer = new StreamWriter(filename);

      // Create the object that will be serialized.
      Orchestra band = new Orchestra();

      // Create an object of the derived type.
      Brass i = new Brass();
      i.Name = "Trumpet";
      i.IsValved = true;
      Instrument[] myInstruments = {i};
      band.Instruments = myInstruments;

      // Serialize the object.
      s.Serialize(writer,band);
      writer.Close();
   }

   public void DeserializeObject(string filename)
   {
      XmlAttributeOverrides attrOverrides =
         new XmlAttributeOverrides();
      XmlAttributes attrs = new XmlAttributes();

      // Create an XmlElementAttribute to override the Instrument.
      XmlElementAttribute attr = new XmlElementAttribute();
      attr.ElementName = "Brass";
      attr.Type = typeof(Brass);

      // Add the XmlElementAttribute to the collection of objects.
      attrs.XmlElements.Add(attr);

      attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);

      // Create the XmlSerializer using the XmlAttributeOverrides.
      XmlSerializer s =
      new XmlSerializer(typeof(Orchestra), attrOverrides);

      FileStream fs = new FileStream(filename, FileMode.Open);
      Orchestra band = (Orchestra) s.Deserialize(fs);
      Console.WriteLine("Brass:");

      /* The difference between deserializing the overridden
      XML document and serializing it is this: To read the derived
      object values, you must declare an object of the derived type
      (Brass), and cast the Instrument instance to it. */
      Brass b;
      foreach(Instrument i in band.Instruments)
      {
         b = (Brass)i;
         Console.WriteLine(
         b.Name + "\n" +
         b.IsValved);
      }
   }
}
Option Explicit
Option Strict

Imports System.IO
Imports System.Xml.Serialization

Public Class Orchestra
    Public Instruments() As Instrument
End Class

Public Class Instrument
    Public Name As String
End Class

Public Class Brass
    Inherits Instrument
    Public IsValved As Boolean
End Class

Public Class Run
    
    Public Shared Sub Main()
        Dim test As New Run()
        test.SerializeObject("Override.xml")
        test.DeserializeObject("Override.xml")
    End Sub
        
    Public Sub SerializeObject(ByVal filename As String)
        ' Each overridden field, property, or type requires
        ' an XmlAttributes object. 
        Dim attrs As New XmlAttributes()
        
        ' Create an XmlElementAttribute to override the
        ' field that returns Instrument objects. The overridden field
        ' returns Brass objects instead. 
        Dim attr As New XmlElementAttribute()
        attr.ElementName = "Brass"
        attr.Type = GetType(Brass)
        
        ' Add the element to the collection of elements.
        attrs.XmlElements.Add(attr)
        
        ' Create the XmlAttributeOverrides object.
        Dim attrOverrides As New XmlAttributeOverrides()
        
        ' Add the type of the class that contains the overridden
        ' member and the XmlAttributes to override it with to the
        ' XmlAttributeOverrides object. 
        attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
        
        ' Create the XmlSerializer using the XmlAttributeOverrides.
        Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
        
        ' Writing the file requires a TextWriter.
        Dim writer As New StreamWriter(filename)
        
        ' Create the object that will be serialized.
        Dim band As New Orchestra()
        
        ' Create an object of the derived type.
        Dim i As New Brass()
        i.Name = "Trumpet"
        i.IsValved = True
        Dim myInstruments() As Instrument = {i}
        band.Instruments = myInstruments
        
        ' Serialize the object.
        s.Serialize(writer, band)
        writer.Close()
    End Sub    
    
    Public Sub DeserializeObject(filename As String)
        Dim attrOverrides As New XmlAttributeOverrides()
        Dim attrs As New XmlAttributes()
        
        ' Create an XmlElementAttribute to override the Instrument.
        Dim attr As New XmlElementAttribute()
        attr.ElementName = "Brass"
        attr.Type = GetType(Brass)
        
        ' Add the XmlElementAttribute to the collection of objects.
        attrs.XmlElements.Add(attr)
        
        attrOverrides.Add(GetType(Orchestra), "Instruments", attrs)
        
        ' Create the XmlSerializer using the XmlAttributeOverrides.
        Dim s As New XmlSerializer(GetType(Orchestra), attrOverrides)
        
        Dim fs As New FileStream(filename, FileMode.Open)
        Dim band As Orchestra = CType(s.Deserialize(fs), Orchestra)
        Console.WriteLine("Brass:")
        
        ' The difference between deserializing the overridden
        ' XML document and serializing it is this: To read the derived
        ' object values, you must declare an object of the derived type
        ' (Brass), and cast the Instrument instance to it. 
        Dim b As Brass
        Dim i As Instrument
        For Each i In  band.Instruments
            b = CType(i, Brass)
            Console.WriteLine(b.Name & ControlChars.Cr & b.IsValved)
        Next i
    End Sub
End Class

Uwagi

Element XmlAttributeOverrides umożliwia XmlSerializer zastąpienie domyślnego sposobu serializacji zestawu obiektów. Zastępowanie serializacji w ten sposób ma dwa zastosowania: najpierw można kontrolować i rozszerzyć serializacji obiektów znajdujących się w dll — nawet jeśli nie masz dostępu do źródła; po drugie, można utworzyć jeden zestaw klas z możliwością serializacji, ale serializować obiekty na wiele sposobów. Na przykład zamiast serializować elementy członkowskie wystąpienia klasy jako elementy XML, można serializować je jako atrybuty XML, co skutkuje bardziej wydajnym dokumentem do transportu.

Po utworzeniu XmlAttributeOverrides obiektu należy przekazać go jako argument do konstruktora XmlSerializer . XmlSerializer Wynikowe używa danych zawartych przez element XmlAttributeOverrides , aby zastąpić atrybuty, które kontrolują sposób serializacji obiektów. W tym XmlAttributeOverrides celu element zawiera kolekcję typów obiektów, które są zastępowane, a także obiekt skojarzony z każdym przesłoniętym typem XmlAttributes obiektu. Sam XmlAttributes obiekt zawiera odpowiedni zestaw obiektów atrybutów, które kontrolują sposób serializacji każdego pola, właściwości lub klasy.

Proces tworzenia i używania XmlAttributeOverrides obiektu jest następujący:

  1. XmlAttributes Utwórz obiekt.

  2. Utwórz obiekt atrybutu, który jest odpowiedni dla obiektu, który jest zastępowany. Aby na przykład zastąpić pole lub właściwość, utwórz XmlElementAttributeobiekt , używając nowego, pochodnego typu. Opcjonalnie można przypisać nowy ElementNameelement lub Namespace zastąpić nazwę atrybutu klasy bazowej lub przestrzeń nazw.

  3. Dodaj obiekt atrybutu do odpowiedniej XmlAttributes właściwości lub kolekcji. Można na przykład dodać element XmlElementAttribute do XmlElements kolekcji XmlAttributes obiektu, określając nazwę elementu członkowskiego, która jest zastępowana.

  4. XmlAttributeOverrides Utwórz obiekt.

  5. Add Za pomocą metody dodaj XmlAttributes obiekt do XmlAttributeOverrides obiektu. Jeśli zastępowany obiekt jest obiektem XmlRootAttribute lub XmlTypeAttribute, należy określić tylko typ przesłoniętego obiektu. Jeśli jednak zastępujesz pole lub właściwość, musisz również określić nazwę przesłoniętego elementu członkowskiego.

  6. Podczas konstruowania XmlSerializerobiektu przekaż element XmlAttributeOverrides do konstruktora XmlSerializer .

  7. Użyj wynikowej XmlSerializer serializacji lub deserializacji obiektów klasy pochodnej.

Konstruktory

XmlAttributeOverrides()

Inicjuje nowe wystąpienie klasy XmlAttributeOverrides.

Właściwości

Item[Type, String]

Pobiera obiekt skojarzony z określonym typem (klasy bazowej). Parametr składowy określa składową klasy bazowej, która jest zastępowana.

Item[Type]

Pobiera obiekt skojarzony z określonym, klasą bazową, typem.

Metody

Add(Type, String, XmlAttributes)

XmlAttributes Dodaje obiekt do kolekcji XmlAttributes obiektów. Parametr type określa obiekt, który ma zostać zastąpiony. Parametr member określa nazwę elementu członkowskiego, który jest zastępowany.

Add(Type, XmlAttributes)

XmlAttributes Dodaje obiekt do kolekcji XmlAttributes obiektów. Parametr type określa obiekt, który ma zostać zastąpiony przez XmlAttributes obiekt.

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Dotyczy

Zobacz też