XmlSerializer 建構函式

定義

初始化 XmlSerializer 類別的新執行個體。

多載

XmlSerializer()

初始化 XmlSerializer 類別的新執行個體。

XmlSerializer(Type)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。

XmlSerializer(XmlTypeMapping)

使用將一個型別對應到另一個型別的物件,初始化 XmlSerializer 類別的執行個體。

XmlSerializer(Type, String)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。 指定所有 XML 項目的預設命名空間。

XmlSerializer(Type, Type[])

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。 如果屬性或欄位傳回陣列,extraTypes 參數就會指定可插入陣列的物件。

XmlSerializer(Type, XmlAttributeOverrides)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。 每個要序列化的物件本身會包含類別執行個體,這個多載可以其他類別覆寫。

XmlSerializer(Type, XmlRootAttribute)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。 它還指定做為 XML 根項目的類別。

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String)

初始化 XmlSerializer 類別的新執行個體,該類別可將 Object 型別的物件序列化為 XML 文件執行個體,並可將 XML 文件執行個體還原序列化為 Object 型別的物件。 每個要序列化的物件本身都可包含類別的執行個體,這個多載會使用其他類別對其進行覆寫。 這個多載也會指定所有 XML 項目的預設命名空間,以及要做為 XML 根項目的類別。

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String)

初始化 XmlSerializer 類別的新執行個體,該類別可將 Object 型別的物件序列化為 XML 文件執行個體,並可將 XML 文件執行個體還原序列化為 Object 型別的物件。 每個要序列化的物件本身都可包含類別的執行個體,這個多載會使用其他類別對其進行覆寫。 這個多載也會指定所有 XML 項目的預設命名空間,以及要做為 XML 根項目的類別。

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence)
已過時。

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件執行個體,並可將 XML 文件執行個體還原序列化為指定型別的物件。 這個多載可讓您提供序列化或還原序列化作業期間遇到的其他型別,以及所有 XML 項目的預設命名空間、用做 XML 根項目的類別及其位置,和存取所需的認證。

XmlSerializer()

初始化 XmlSerializer 類別的新執行個體。

C#
protected XmlSerializer ();

適用於

.NET 7 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1
UWP 10.0

XmlSerializer(Type)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。

C#
public XmlSerializer (Type type);

參數

type
Type

這個 XmlSerializer 可序列化的物件型別。

範例

下列範例會建構串列 XmlSerializer 化名為 Widget 之物件的 。 此範例會先設定 物件的各種屬性,再呼叫 Serialize 方法。

C#
private void SerializeObject(string filename)
{
   XmlSerializer serializer =
   new XmlSerializer(typeof(OrderedItem));

   // Create an instance of the class to be serialized.
   OrderedItem i = new OrderedItem();

   // Set the public property values.
   i.ItemName = "Widget";
   i.Description = "Regular Widget";
   i.Quantity = 10;
   i.UnitPrice = (decimal) 2.30;

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

   // Serialize the object, and close the TextWriter.
   serializer.Serialize(writer, i);
   writer.Close();
}

// This is the class that will be serialized.
public class OrderedItem
{
   public string ItemName;
   public string Description;
   public decimal UnitPrice;
   public int Quantity;
}

備註

一般而言,應用程式會定義數個類別,該 XmlSerializer 類別會轉換成單一 XML 實例檔。 不過, XmlSerializer 必須只知道一個類型,也就是代表 XML 根項目的類別類型。 會自動 XmlSerializer 序列化所有次級類別實例。 同樣地,還原序列化只需要 XML 根項目的類型。

另請參閱

適用於

.NET 7 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1
UWP 10.0

XmlSerializer(XmlTypeMapping)

使用將一個型別對應到另一個型別的物件,初始化 XmlSerializer 類別的執行個體。

C#
public XmlSerializer (System.Xml.Serialization.XmlTypeMapping xmlTypeMapping);

參數

xmlTypeMapping
XmlTypeMapping

將某個型別對應至另一個型別的 XmlTypeMapping

範例

下列範例會序列化名為 的 Group 類別。 會覆寫 、 IgnoreThis 欄位和列舉成員的 GroupType 序列化 GroupName 。 在 方法中 CreateOverrideSerializer SoapAttributeOverrides ,會建立 物件,並針對每個覆寫的成員或列舉 SoapAttributes ,建立物件時會設定適當的屬性並新增至 SoapAttributeOverrides 物件。 XmlMapping物件是使用 SoapAttributeOverrides 物件建立的,而該 XmlMapping 物件用來建立 XmlSerializer 覆寫預設序列化的 。

C#
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;

public class Group
{
   [SoapAttribute (Namespace = "http://www.cpandl.com")]
   public string GroupName;

   [SoapAttribute(DataType = "base64Binary")]
   public Byte [] GroupNumber;

   [SoapAttribute(DataType = "date", AttributeName = "CreationDate")]
   public DateTime Today;
   [SoapElement(DataType = "nonNegativeInteger", ElementName = "PosInt")]
   public string PostitiveInt;
   // This is ignored when serialized unless it's overridden.
   [SoapIgnore]
   public bool IgnoreThis;

   public GroupType Grouptype;

   public Vehicle MyVehicle;

   // The SoapInclude allows the method to return a Car.
   [SoapInclude(typeof(Car))]
   public Vehicle myCar(string licNumber)
   {
      Vehicle v;
      if(licNumber == "")
         {
            v = new Car();
        v.licenseNumber = "!!!!!!";
     }
      else
     {
       v = new Car();
       v.licenseNumber = licNumber;
     }
      return v;
   }
}

// SoapInclude allows Vehicle to accept Car type.
[SoapInclude(typeof(Car))]
public abstract class Vehicle
{
   public string licenseNumber;
   public DateTime makeDate;
}

public class Car: Vehicle
{
}

public enum GroupType
{
   // These enums can be overridden.
   [SoapEnum("Small")]
   A,
   [SoapEnum("Large")]
   B
}

public class Run
{
   public static void Main()
   {
      Run test = new Run();
      test.SerializeOriginal("SoapOriginal.xml");
      test.SerializeOverride("SoapOverrides.xml");
      test.DeserializeOriginal("SoapOriginal.xml");
      test.DeserializeOverride("SoapOverrides.xml");
   }
   public void SerializeOriginal(string filename)
   {
      // Create an instance of the XmlSerializer class.
      XmlTypeMapping myMapping =
      (new SoapReflectionImporter().ImportTypeMapping(
      typeof(Group)));
      XmlSerializer mySerializer =
      new XmlSerializer(myMapping);
      Group myGroup=MakeGroup();
      // Writing the file requires a TextWriter.
      XmlTextWriter writer =
      new XmlTextWriter(filename, Encoding.UTF8);
      writer.Formatting = Formatting.Indented;
      writer.WriteStartElement("wrapper");
      // Serialize the class, and close the TextWriter.
      mySerializer.Serialize(writer, myGroup);
      writer.WriteEndElement();
      writer.Close();
   }

   public void SerializeOverride(string filename)
   {
      // Create an instance of the XmlSerializer class
      // that overrides the serialization.
      XmlSerializer overRideSerializer = CreateOverrideSerializer();
      Group myGroup=MakeGroup();
      // Writing the file requires a TextWriter.
      XmlTextWriter writer =
      new XmlTextWriter(filename, Encoding.UTF8);
      writer.Formatting = Formatting.Indented;
      writer.WriteStartElement("wrapper");
      // Serialize the class, and close the TextWriter.
      overRideSerializer.Serialize(writer, myGroup);
      writer.WriteEndElement();
      writer.Close();
   }

   private Group MakeGroup(){
      // Create an instance of the class that will be serialized.
      Group myGroup = new Group();

      // Set the object properties.
      myGroup.GroupName = ".NET";

      Byte [] hexByte = new Byte[2]{Convert.ToByte(100),
      Convert.ToByte(50)};
      myGroup.GroupNumber = hexByte;

      DateTime myDate = new DateTime(2002,5,2);
      myGroup.Today = myDate;
      myGroup.PostitiveInt= "10000";
      myGroup.IgnoreThis=true;
      myGroup.Grouptype= GroupType.B;
      Car thisCar =(Car)  myGroup.myCar("1234566");
      myGroup.MyVehicle=thisCar;
      return myGroup;
   }   	

   public void DeserializeOriginal(string filename)
   {
      // Create an instance of the XmlSerializer class.
      XmlTypeMapping myMapping =
      (new SoapReflectionImporter().ImportTypeMapping(
      typeof(Group)));
      XmlSerializer mySerializer =
      new XmlSerializer(myMapping);

      // Reading the file requires an  XmlTextReader.
      XmlTextReader reader=
      new XmlTextReader(filename);
      reader.ReadStartElement("wrapper");

      // Deserialize and cast the object.
      Group myGroup;
      myGroup = (Group) mySerializer.Deserialize(reader);
      reader.ReadEndElement();
      reader.Close();
   }

   public void DeserializeOverride(string filename)
   {
      // Create an instance of the XmlSerializer class.
      XmlSerializer overRideSerializer = CreateOverrideSerializer();

      // Reading the file requires an  XmlTextReader.
      XmlTextReader reader=
      new XmlTextReader(filename);
      reader.ReadStartElement("wrapper");

      // Deserialize and cast the object.
      Group myGroup;
      myGroup = (Group) overRideSerializer.Deserialize(reader);
      reader.ReadEndElement();
      reader.Close();
      ReadGroup(myGroup);
   }

   private void ReadGroup(Group myGroup){
      Console.WriteLine(myGroup.GroupName);
      Console.WriteLine(myGroup.GroupNumber[0]);
      Console.WriteLine(myGroup.GroupNumber[1]);
      Console.WriteLine(myGroup.Today);
      Console.WriteLine(myGroup.PostitiveInt);
      Console.WriteLine(myGroup.IgnoreThis);
      Console.WriteLine();
   }
   private XmlSerializer CreateOverrideSerializer()
   {
      SoapAttributeOverrides mySoapAttributeOverrides =
      new SoapAttributeOverrides();
      SoapAttributes soapAtts = new SoapAttributes();

      SoapElementAttribute mySoapElement = new SoapElementAttribute();
      mySoapElement.ElementName = "xxxx";
      soapAtts.SoapElement = mySoapElement;
      mySoapAttributeOverrides.Add(typeof(Group), "PostitiveInt",
      soapAtts);

      // Override the IgnoreThis property.
      SoapIgnoreAttribute myIgnore = new SoapIgnoreAttribute();
      soapAtts = new SoapAttributes();
      soapAtts.SoapIgnore = false;
      mySoapAttributeOverrides.Add(typeof(Group), "IgnoreThis",
      soapAtts);

      // Override the GroupType enumeration.	
      soapAtts = new SoapAttributes();
      SoapEnumAttribute xSoapEnum = new SoapEnumAttribute();
      xSoapEnum.Name = "Over1000";
      soapAtts.SoapEnum = xSoapEnum;

      // Add the SoapAttributes to the
      // mySoapAttributeOverridesrides object.
      mySoapAttributeOverrides.Add(typeof(GroupType), "A",
      soapAtts);

      // Create second enumeration and add it.
      soapAtts = new SoapAttributes();
      xSoapEnum = new SoapEnumAttribute();
      xSoapEnum.Name = "ZeroTo1000";
      soapAtts.SoapEnum = xSoapEnum;
      mySoapAttributeOverrides.Add(typeof(GroupType), "B",
      soapAtts);

      // Override the Group type.
      soapAtts = new SoapAttributes();
      SoapTypeAttribute soapType = new SoapTypeAttribute();
      soapType.TypeName = "Team";
      soapAtts.SoapType = soapType;
      mySoapAttributeOverrides.Add(typeof(Group),soapAtts);

      // Create an XmlTypeMapping that is used to create an instance
      // of the XmlSerializer. Then return the XmlSerializer object.
      XmlTypeMapping myMapping = (new SoapReflectionImporter(
      mySoapAttributeOverrides)).ImportTypeMapping(typeof(Group));
    
      XmlSerializer ser = new XmlSerializer(myMapping);
      return ser;
   }
}

備註

當您將物件序列化為 SOAP 訊息時,會使用此建構函式來建立 XmlSerializer 。 若要控制產生的 SOAP 訊息,請使用特殊屬性 (開頭為命名空間中找到 System.Xml.Serialization 的 「Soap」) 字。

另請參閱

適用於

.NET 7 和其他版本
產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1

XmlSerializer(Type, String)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。 指定所有 XML 項目的預設命名空間。

C#
public XmlSerializer (Type type, string defaultNamespace);
C#
public XmlSerializer (Type type, string? defaultNamespace);

參數

type
Type

這個 XmlSerializer 可序列化的物件型別。

defaultNamespace
String

用於所有 XML 項目的預設命名空間。

範例

下列範例會 XmlSerializer 建構序列化名為 Widget 之物件的 。 此範例會先設定 物件的各種屬性,然後再呼叫 Serialize 方法。

C#
private void SerializeObject(string filename) {
    XmlSerializer serializer = new XmlSerializer
        (typeof(OrderedItem), "http://www.cpandl.com");

    // Create an instance of the class to be serialized.
    OrderedItem i = new OrderedItem();

    // Insert code to set property values.

    // Writing the document requires a TextWriter.
    TextWriter writer = new StreamWriter(filename);
    // Serialize the object, and close the TextWriter
    serializer.Serialize(writer, i);
    writer.Close();
}

private void DeserializeObject(string filename) {
    XmlSerializer serializer = new XmlSerializer
        (typeof(OrderedItem), "http://www.cpandl.com");
    // A FileStream is needed to read the XML document.
    FileStream fs = new FileStream(filename, FileMode.Open);

    // Declare an object variable of the type to be deserialized.
    OrderedItem i;

    // Deserialize the object.
    i = (OrderedItem) serializer.Deserialize(fs);

    // Insert code to use the properties and methods of the object.
}

另請參閱

適用於

.NET 7 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1
UWP 10.0

XmlSerializer(Type, Type[])

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。 如果屬性或欄位傳回陣列,extraTypes 參數就會指定可插入陣列的物件。

C#
public XmlSerializer (Type type, Type[] extraTypes);
C#
public XmlSerializer (Type type, Type[]? extraTypes);

參數

type
Type

這個 XmlSerializer 可序列化的物件型別。

extraTypes
Type[]

要序列化之其他物件型別的 Type 陣列。

範例

下列範例會序列化類別的實例,其中包含傳回 物件陣列的公用欄位。 建 extraTypes 構函式的 XmlSerializer 參數會指定可在陣列中序列化之物件的類型。

C#
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

// This defines the object that will be serialized.
public class Teacher
{
   public string Name;
   public Teacher(){}
   /* Note that the Info field returns an array of objects.
      Any object can be added to the array by adding the
      object type to the array passed to the extraTypes argument. */
   [XmlArray (ElementName = "ExtraInfo", IsNullable = true)]
   public object[] Info;
   public Phone PhoneInfo;
}

// This defines one of the extra types to be included.
public class Address
{
   public string City;

   public Address(){}
   public Address(string city)
   {
      City = city;
   }
}

// Another extra type to include.
public class Phone
{
   public string PhoneNumber;
   public Phone(){}
   public Phone(string phoneNumber)
   {
      PhoneNumber = phoneNumber;
   }
}

// Another type, derived from Phone
public class InternationalPhone:Phone
{
   public string CountryCode;

   public InternationalPhone(){}

   public InternationalPhone(string countryCode)
   {
      CountryCode = countryCode;
   }
}

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

   private void SerializeObject(string filename)
   {
      // Writing the file requires a TextWriter.
      TextWriter myStreamWriter = new StreamWriter(filename);

      // Create a Type array.
      Type [] extraTypes= new Type[3];
      extraTypes[0] = typeof(Address);
      extraTypes[1] = typeof(Phone);
      extraTypes[2] = typeof(InternationalPhone);

      // Create the XmlSerializer instance.
      XmlSerializer mySerializer = new XmlSerializer
      (typeof(Teacher),extraTypes);

      Teacher teacher = new Teacher();
      teacher.Name = "Mike";
      // Add extra types to the Teacher object
      object [] info = new object[2];
      info[0] = new Address("Springville");
      info[1] = new Phone("555-0100");

      teacher.Info = info;

      teacher.PhoneInfo = new InternationalPhone("000");

      mySerializer.Serialize(myStreamWriter,teacher);
      myStreamWriter.Close();
   }

   private void DeserializeObject(string filename)
   {
      // Create a Type array.
      Type [] extraTypes= new Type[3];
      extraTypes[0] = typeof(Address);
      extraTypes[1] = typeof(Phone);
      extraTypes[2] = typeof(InternationalPhone);

      // Create the XmlSerializer instance.
      XmlSerializer mySerializer = new XmlSerializer
      (typeof(Teacher),extraTypes);

      // Reading a file requires a FileStream.
      FileStream fs = new FileStream(filename, FileMode.Open);
      Teacher teacher = (Teacher) mySerializer.Deserialize(fs);

      // Read the extra information.
      Address a = (Address)teacher.Info[0];
      Phone p = (Phone) teacher.Info[1];
      InternationalPhone Ip =
      (InternationalPhone) teacher.PhoneInfo;

      Console.WriteLine(teacher.Name);
      Console.WriteLine(a.City);
      Console.WriteLine(p.PhoneNumber);
      Console.WriteLine(Ip.CountryCode);
   }
}

備註

根據預設,如果公用屬性或欄位傳回物件或物件的陣列,就會自動序列化物件類型。 不過,如果類別包含傳回 型 Object 別陣列的欄位或屬性,則可以將任何物件插入該陣列中。 在此情況下,必須指示 , XmlSerializer 預期所有可能的物件類型都 Object 插入陣列中。 若要這樣做,請使用 extraTypes 參數來指定要序列化或還原序列化的額外物件類型。

您也可以使用 extraTypes 參數來指定衍生自基類的類型。 例如,假設名為 的基類 Phone 存在,而名為 的 InternationalPhone 類別衍生自該基類。 extraTypes使用 參數也可以指定衍生型別。

另請參閱

適用於

.NET 7 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1
UWP 10.0

XmlSerializer(Type, XmlAttributeOverrides)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。 每個要序列化的物件本身會包含類別執行個體,這個多載可以其他類別覆寫。

C#
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides overrides);
C#
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides? overrides);

參數

type
Type

要序列化的物件型別。

範例

下列範例會序列化 DLL 中定義之類別的實例,並執行此動作,覆寫 DLL 中找到的公用成員。

C#
// Beginning of HighSchool.dll
namespace HighSchool
{
   public class Student
   {
      public string Name;
      public int ID;
   }

   public class MyClass
   {
      public Student[] Students;
   }
}

namespace College
   {
   using System;
   using System.IO;
   using System.Xml;
   using System.Xml.Serialization;
   using HighSchool;

    public class Graduate:HighSchool.Student
    {
       public Graduate(){}
       // Add a new field named University.
       public string University;
    }

   public class Run
   {
      public static void Main()
      {
         Run test = new Run();
         test.WriteOverriddenAttributes("College.xml");
         test.ReadOverriddenAttributes("College.xml");
      }

      private void WriteOverriddenAttributes(string filename)
      {
         // Writing the file requires a TextWriter.
         TextWriter myStreamWriter = new StreamWriter(filename);
         // Create an XMLAttributeOverrides class.
         XmlAttributeOverrides attrOverrides =
         new XmlAttributeOverrides();
         // Create the XmlAttributes class.
         XmlAttributes attrs = new XmlAttributes();

         /* Override the Student class. "Alumni" is the name
         of the overriding element in the XML output. */
         XmlElementAttribute attr =
         new XmlElementAttribute("Alumni", typeof(Graduate));

         /* Add the XmlElementAttribute to the collection of
         elements in the XmlAttributes object. */
         attrs.XmlElements.Add(attr);

         /* Add the XmlAttributes to the XmlAttributeOverrides.
         "Students" is the name being overridden. */
         attrOverrides.Add(typeof(HighSchool.MyClass),
         "Students", attrs);

         // Create the XmlSerializer.
         XmlSerializer mySerializer = new XmlSerializer
         (typeof(HighSchool.MyClass), attrOverrides);

         MyClass myClass = new MyClass();

         Graduate g1 = new Graduate();
         g1.Name = "Jackie";
         g1.ID = 1;
         g1.University = "Alma Mater";

         Graduate g2 = new Graduate();
         g2.Name = "Megan";
         g2.ID = 2;
         g2.University = "CM";

         Student[] myArray = {g1,g2};
         myClass.Students = myArray;

         mySerializer.Serialize(myStreamWriter, myClass);
         myStreamWriter.Close();
      }

      private void ReadOverriddenAttributes(string filename)
      {
         /* The majority of the code here is the same as that in the
         WriteOverriddenAttributes method. Because the XML being read
         doesn't conform to the schema defined by the DLL, the
         XMLAttributesOverrides must be used to create an
         XmlSerializer instance to read the XML document.*/

         XmlAttributeOverrides attrOverrides = new
         XmlAttributeOverrides();
         XmlAttributes attrs = new XmlAttributes();
         XmlElementAttribute attr =
         new XmlElementAttribute("Alumni", typeof(Graduate));
         attrs.XmlElements.Add(attr);
         attrOverrides.Add(typeof(HighSchool.MyClass),
         "Students", attrs);

         XmlSerializer readSerializer = new XmlSerializer
         (typeof(HighSchool.MyClass), attrOverrides);

         // To read the file, a FileStream object is required.
         FileStream fs = new FileStream(filename, FileMode.Open);

         MyClass myClass;

         myClass = (MyClass) readSerializer.Deserialize(fs);

         /* Here is the difference between reading and writing an
         XML document: You must declare an object of the derived
         type (Graduate) and cast the Student instance to it.*/
         Graduate g;

         foreach(Graduate grad in myClass.Students)
         {
            g = (Graduate) grad;
            Console.Write(g.Name + "\t");
            Console.Write(g.ID + "\t");
            Console.Write(g.University + "\n");
         }
      }
   }
}

備註

參數 overrides 可用來控制欄位和屬性在 XML 中編碼的方式。 這些設定會覆寫物件上已經存在的任何屬性。 當無法修改原始程式碼或相同類別需要多個編碼時,這非常有用。

另請參閱

適用於

.NET 7 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1
UWP 10.0

XmlSerializer(Type, XmlRootAttribute)

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件,並可將 XML 文件還原序列化為指定型別的物件。 它還指定做為 XML 根項目的類別。

C#
public XmlSerializer (Type type, System.Xml.Serialization.XmlRootAttribute root);
C#
public XmlSerializer (Type type, System.Xml.Serialization.XmlRootAttribute? root);

參數

type
Type

這個 XmlSerializer 可序列化的物件型別。

root
XmlRootAttribute

表示 XML 根項目的 XmlRootAttribute

範例

下列範例會 XmlSerializer 建構使用 XmlRootAttribute ,其中包含 XML 根項目的各種屬性,例如其命名空間和元素名稱。

C#
private void SerializeObject(string filename) {
    // Create an XmlRootAttribute, and set its properties.
    XmlRootAttribute xRoot = new XmlRootAttribute();
    xRoot.ElementName = "CustomRoot";
    xRoot.Namespace = "http://www.cpandl.com";
    xRoot.IsNullable = true;

    // Construct the XmlSerializer with the XmlRootAttribute.
    XmlSerializer serializer = new XmlSerializer
        (typeof(OrderedItem),xRoot);

    // Create an instance of the object to serialize.
    OrderedItem i = new OrderedItem();
    // Insert code to set properties of the ordered item.

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

    serializer.Serialize(writer, i);
    writer.Close();
}

private void DeserializeObject(string filename) {
    // Create an XmlRootAttribute, and set its properties.
    XmlRootAttribute xRoot = new XmlRootAttribute();
    xRoot.ElementName = "CustomRoot";
    xRoot.Namespace = "http://www.cpandl.com";
    xRoot.IsNullable = true;

    XmlSerializer serializer = new XmlSerializer
        (typeof(OrderedItem),xRoot);

    // A FileStream is needed to read the XML document.
    FileStream fs = new FileStream(filename, FileMode.Open);
    // Deserialize the object.
    OrderedItem i = (OrderedItem) serializer.Deserialize(fs);
    // Insert code to use the object's properties and methods.
}

備註

XML 檔的根項目會括住所有其他元素。 根據預設,參數所 type 指定的物件會序列化為根項目。 屬性,例如根項目的 XML 專案名稱,取自 type 物件。 不過,參數 root 可讓您藉由指定 XmlRootAttribute 來取代預設物件的資訊;物件可讓您設定不同的命名空間、元素名稱等等。

另請參閱

適用於

.NET 7 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1
UWP 10.0

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String)

初始化 XmlSerializer 類別的新執行個體,該類別可將 Object 型別的物件序列化為 XML 文件執行個體,並可將 XML 文件執行個體還原序列化為 Object 型別的物件。 每個要序列化的物件本身都可包含類別的執行個體,這個多載會使用其他類別對其進行覆寫。 這個多載也會指定所有 XML 項目的預設命名空間,以及要做為 XML 根項目的類別。

C#
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace);
C#
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides? overrides, Type[]? extraTypes, System.Xml.Serialization.XmlRootAttribute? root, string? defaultNamespace);

參數

type
Type

這個 XmlSerializer 可序列化的物件型別。

overrides
XmlAttributeOverrides

XmlAttributeOverrides,延伸或覆寫指定在 type 參數中類別的行為。

extraTypes
Type[]

要序列化之其他物件型別的 Type 陣列。

root
XmlRootAttribute

定義 XML 根項目屬性的 XmlRootAttribute

defaultNamespace
String

XML 文件中所有 XML 項目的預設命名空間。

範例

下列範例會序列化 DLL 中定義之類別的實例,並執行此動作,覆寫 類別中找到的公用成員。 此範例也會指定額外類型的陣列、所有 XML 專案的預設命名空間,以及提供 XML 根項目資訊的類別。 此範例假設開頭的程式碼已編譯成名為 HighSchool 的 DLL。

C#
// Beginning of the HighSchool.dll

namespace HighSchool
{
   public class Student
   {
      public string Name;
      public int ID;
   }

   public class MyClass
   {
      public Student[] Students;
   }
}

namespace College
   {
   using System;
   using System.IO;
   using System.Xml;
   using System.Xml.Serialization;
   using HighSchool;

    public class Graduate:HighSchool.Student
    {
       public Graduate(){}
       // Add a new field named University.
       public string University;
       // Use extra types to use this field.
       public object[]Info;
    }

    public class Address
    {
       public string City;
    }

    public class Phone
    {
       public string Number;
    }

   public class Run
   {
      public static void Main()
      {
         Run test = new Run();
         test.WriteOverriddenAttributes("College.xml");
         test.ReadOverriddenAttributes("College.xml");
      }

      private void WriteOverriddenAttributes(string filename)
      {
         // Writing the file requires a TextWriter.
         TextWriter myStreamWriter = new StreamWriter(filename);
         // Create an XMLAttributeOverrides class.
         XmlAttributeOverrides attrOverrides =
         new XmlAttributeOverrides();
         // Create the XmlAttributes class.
         XmlAttributes attrs = new XmlAttributes();
         /* Override the Student class. "Alumni" is the name
         of the overriding element in the XML output. */

         XmlElementAttribute attr =
         new XmlElementAttribute("Alumni", typeof(Graduate));
         /* Add the XmlElementAttribute to the collection of
         elements in the XmlAttributes object. */
         attrs.XmlElements.Add(attr);
         /* Add the XmlAttributes to the XmlAttributeOverrides.
         "Students" is the name being overridden. */
         attrOverrides.Add(typeof(HighSchool.MyClass),
         "Students", attrs);

         // Create array of extra types.
         Type [] extraTypes = new Type[2];
         extraTypes[0]=typeof(Address);
         extraTypes[1]=typeof(Phone);

         // Create an XmlRootAttribute.
         XmlRootAttribute root = new XmlRootAttribute("Graduates");

         /* Create the XmlSerializer with the
         XmlAttributeOverrides object. */
         XmlSerializer mySerializer = new XmlSerializer
         (typeof(HighSchool.MyClass), attrOverrides, extraTypes,
         root, "http://www.microsoft.com");

         MyClass myClass= new MyClass();

         Graduate g1 = new Graduate();
         g1.Name = "Jacki";
         g1.ID = 1;
         g1.University = "Alma";

         Graduate g2 = new Graduate();
         g2.Name = "Megan";
         g2.ID = 2;
         g2.University = "CM";

         Student[] myArray = {g1,g2};

         myClass.Students = myArray;

         // Create extra information.
         Address a1 = new Address();
         a1.City = "Ionia";
         Address a2 = new Address();
         a2.City = "Stamford";
         Phone p1 = new Phone();
         p1.Number = "555-0101";
         Phone p2 = new Phone();
         p2.Number = "555-0100";

         Object[]o1 = new Object[2]{a1, p1};
         Object[]o2 = new Object[2]{a2,p2};

         g1.Info = o1;
         g2.Info = o2;
         mySerializer.Serialize(myStreamWriter,myClass);
         myStreamWriter.Close();
      }

      private void ReadOverriddenAttributes(string filename)
      {
         /* The majority of the code here is the same as that in the
         WriteOverriddenAttributes method. Because the XML being read
         doesn't conform to the schema defined by the DLL, the
         XMLAttributesOverrides must be used to create an
         XmlSerializer instance to read the XML document.*/

         XmlAttributeOverrides attrOverrides = new
         XmlAttributeOverrides();
         XmlAttributes attrs = new XmlAttributes();
         XmlElementAttribute attr =
         new XmlElementAttribute("Alumni", typeof(Graduate));
         attrs.XmlElements.Add(attr);
         attrOverrides.Add(typeof(HighSchool.MyClass),
         "Students", attrs);

         Type [] extraTypes = new Type[2];
         extraTypes[0] = typeof(Address);
         extraTypes[1] = typeof(Phone);

         XmlRootAttribute root = new XmlRootAttribute("Graduates");

         XmlSerializer readSerializer = new XmlSerializer
         (typeof(HighSchool.MyClass), attrOverrides, extraTypes,
         root, "http://www.microsoft.com");

         // A FileStream object is required to read the file.
         FileStream fs = new FileStream(filename, FileMode.Open);

         MyClass myClass;
         myClass = (MyClass) readSerializer.Deserialize(fs);

         /* Here is the difference between reading and writing an
         XML document: You must declare an object of the derived
         type (Graduate) and cast the Student instance to it.*/
         Graduate g;
         Address a;
         Phone p;
         foreach(Graduate grad in myClass.Students)
         {
            g = (Graduate) grad;
            Console.Write(g.Name + "\t");
            Console.Write(g.ID + "\t");
            Console.Write(g.University + "\n");
            a = (Address) g.Info[0];
            Console.WriteLine(a.City);
            p = (Phone) g.Info[1];
            Console.WriteLine(p.Number);
         }
      }
   }
}

備註

參數 overrides 允許建立 XmlSerializer 序列化擴充或覆寫基類行為的類別。 例如,假設有 DLL,就可以建立繼承或擴充 DLL 中包含的類別。 若要序列化這類類別,您必須在建構 XmlSerializer 時使用 類別的 XmlAttributeOverrides 實例。 如需詳細資訊,請參閱 XmlAttributeOverrides

根據預設,如果公用屬性或欄位傳回物件或物件的陣列,就會自動序列化物件類型。 不過,如果類別包含傳回 型 Object 別陣列的欄位或屬性,則可以將任何物件插入該陣列中。 在此情況下,必須指示 , XmlSerializer 預期所有可能的物件類型都 Object 插入陣列中。 若要這樣做,請使用 extraTypes 參數來指定要序列化或還原序列化的額外物件類型。

XML 檔的根項目會括住所有其他元素。 根據預設,參數所 type 指定的物件會序列化為根項目。 屬性,例如根項目的 XML 專案名稱會取自 type 物件。 不過,參數 root 可讓您藉由指定 XmlRootAttribute 來取代預設物件的資訊;物件可讓您設定不同的命名空間、元素名稱等等。

defaultName使用 參數來指定 所 XmlSerializer 產生之所有 XML 專案的預設命名空間。

另請參閱

適用於

.NET 7 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1
UWP 10.0

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String)

初始化 XmlSerializer 類別的新執行個體,該類別可將 Object 型別的物件序列化為 XML 文件執行個體,並可將 XML 文件執行個體還原序列化為 Object 型別的物件。 每個要序列化的物件本身都可包含類別的執行個體,這個多載會使用其他類別對其進行覆寫。 這個多載也會指定所有 XML 項目的預設命名空間,以及要做為 XML 根項目的類別。

C#
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides? overrides, Type[]? extraTypes, System.Xml.Serialization.XmlRootAttribute? root, string? defaultNamespace, string? location);
C#
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace, string location);

參數

type
Type

這個 XmlSerializer 可序列化的物件型別。

overrides
XmlAttributeOverrides

XmlAttributeOverrides,延伸或覆寫指定在 type 參數中類別的行為。

extraTypes
Type[]

要序列化之其他物件型別的 Type 陣列。

root
XmlRootAttribute

定義 XML 根項目屬性的 XmlRootAttribute

defaultNamespace
String

XML 文件中所有 XML 項目的預設命名空間。

location
String

型別的位置。

適用於

.NET 7 和其他版本
產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 2.0, 2.1

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence)

警告

This method is obsolete and will be removed in a future release of the .NET Framework. Please use a XmlSerializer constructor overload which does not take an Evidence parameter. See http://go2.microsoft.com/fwlink/?LinkId=131738 for more information.

初始化 XmlSerializer 類別的新執行個體,該類別可將指定型別的物件序列化為 XML 文件執行個體,並可將 XML 文件執行個體還原序列化為指定型別的物件。 這個多載可讓您提供序列化或還原序列化作業期間遇到的其他型別,以及所有 XML 項目的預設命名空間、用做 XML 根項目的類別及其位置,和存取所需的認證。

C#
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace, string location, System.Security.Policy.Evidence evidence);
C#
[System.Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use a XmlSerializer constructor overload which does not take an Evidence parameter. See http://go2.microsoft.com/fwlink/?LinkId=131738 for more information.")]
public XmlSerializer (Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace, string location, System.Security.Policy.Evidence evidence);

參數

type
Type

這個 XmlSerializer 可序列化的物件型別。

overrides
XmlAttributeOverrides

XmlAttributeOverrides,延伸或覆寫指定在 type 參數中類別的行為。

extraTypes
Type[]

要序列化之其他物件型別的 Type 陣列。

root
XmlRootAttribute

定義 XML 根項目屬性的 XmlRootAttribute

defaultNamespace
String

XML 文件中所有 XML 項目的預設命名空間。

location
String

型別的位置。

evidence
Evidence

Evidence 類別的執行個體,包含存取型別所需的認證。

屬性

備註

允許更精確地控制對臨時目錄的存取,並防止程式碼插入和惡意探索。 若要使用此方法,請指定位置,並只授與特定使用者的存取權。 系統管理員可以使用符合辨識項與許可權的辨識項清單來設定原則。

適用於

.NET Framework 4.8 和其他版本
產品 版本 (已過時)
.NET Framework 2.0, 3.0, 3.5 (4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8)