XmlSerializer 类

定义

在对象和 XML 文档之间进行序列化和反序列化操作。 XmlSerializer 使您得以控制如何将对象编码到 XML 中。

public class XmlSerializer
继承
XmlSerializer

示例

以下示例包含两个main类: PurchaseOrderTest。 类 PurchaseOrder 包含有关单个购买的信息。 类 Test 包含创建采购订单并读取所创建采购订单的方法。

using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

/* The XmlRootAttribute allows you to set an alternate name
   (PurchaseOrder) of the XML element, the element namespace; by
   default, the XmlSerializer uses the class name. The attribute
   also allows you to set the XML namespace for the element.  Lastly,
   the attribute sets the IsNullable property, which specifies whether
   the xsi:null attribute appears if the class instance is set to
   a null reference. */
[XmlRootAttribute("PurchaseOrder", Namespace="http://www.cpandl.com",
IsNullable = false)]
public class PurchaseOrder
{
   public Address ShipTo;
   public string OrderDate;
   /* The XmlArrayAttribute changes the XML element name
    from the default of "OrderedItems" to "Items". */
   [XmlArrayAttribute("Items")]
   public OrderedItem[] OrderedItems;
   public decimal SubTotal;
   public decimal ShipCost;
   public decimal TotalCost;
}

public class Address
{
   /* The XmlAttribute instructs the XmlSerializer to serialize the Name
      field as an XML attribute instead of an XML element (the default
      behavior). */
   [XmlAttribute]
   public string Name;
   public string Line1;

   /* Setting the IsNullable property to false instructs the
      XmlSerializer that the XML attribute will not appear if
      the City field is set to a null reference. */
   [XmlElementAttribute(IsNullable = false)]
   public string City;
   public string State;
   public string Zip;
}

public class OrderedItem
{
   public string ItemName;
   public string Description;
   public decimal UnitPrice;
   public int Quantity;
   public decimal LineTotal;

   /* Calculate is a custom method that calculates the price per item,
      and stores the value in a field. */
   public void Calculate()
   {
      LineTotal = UnitPrice * Quantity;
   }
}

public class Test
{
   public static void Main()
   {
      // Read and write purchase orders.
      Test t = new Test();
      t.CreatePO("po.xml");
      t.ReadPO("po.xml");
   }

   private void CreatePO(string filename)
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to serialize.
      XmlSerializer serializer =
      new XmlSerializer(typeof(PurchaseOrder));
      TextWriter writer = new StreamWriter(filename);
      PurchaseOrder po=new PurchaseOrder();

      // Create an address to ship and bill to.
      Address billAddress = new Address();
      billAddress.Name = "Teresa Atkinson";
      billAddress.Line1 = "1 Main St.";
      billAddress.City = "AnyTown";
      billAddress.State = "WA";
      billAddress.Zip = "00000";
      // Set ShipTo and BillTo to the same addressee.
      po.ShipTo = billAddress;
      po.OrderDate = System.DateTime.Now.ToLongDateString();

      // Create an OrderedItem object.
      OrderedItem i1 = new OrderedItem();
      i1.ItemName = "Widget S";
      i1.Description = "Small widget";
      i1.UnitPrice = (decimal) 5.23;
      i1.Quantity = 3;
      i1.Calculate();

      // Insert the item into the array.
      OrderedItem [] items = {i1};
      po.OrderedItems = items;
      // Calculate the total cost.
      decimal subTotal = new decimal();
      foreach(OrderedItem oi in items)
      {
         subTotal += oi.LineTotal;
      }
      po.SubTotal = subTotal;
      po.ShipCost = (decimal) 12.51;
      po.TotalCost = po.SubTotal + po.ShipCost;
      // Serialize the purchase order, and close the TextWriter.
      serializer.Serialize(writer, po);
      writer.Close();
   }

   protected void ReadPO(string filename)
   {
      // Create an instance of the XmlSerializer class;
      // specify the type of object to be deserialized.
      XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
      /* If the XML document has been altered with unknown
      nodes or attributes, handle them with the
      UnknownNode and UnknownAttribute events.*/
      serializer.UnknownNode+= new
      XmlNodeEventHandler(serializer_UnknownNode);
      serializer.UnknownAttribute+= new
      XmlAttributeEventHandler(serializer_UnknownAttribute);

      // 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.
      PurchaseOrder po;
      /* Use the Deserialize method to restore the object's state with
      data from the XML document. */
      po = (PurchaseOrder) serializer.Deserialize(fs);
      // Read the order date.
      Console.WriteLine ("OrderDate: " + po.OrderDate);

      // Read the shipping address.
      Address shipTo = po.ShipTo;
      ReadAddress(shipTo, "Ship To:");
      // Read the list of ordered items.
      OrderedItem [] items = po.OrderedItems;
      Console.WriteLine("Items to be shipped:");
      foreach(OrderedItem oi in items)
      {
         Console.WriteLine("\t"+
         oi.ItemName + "\t" +
         oi.Description + "\t" +
         oi.UnitPrice + "\t" +
         oi.Quantity + "\t" +
         oi.LineTotal);
      }
      // Read the subtotal, shipping cost, and total cost.
      Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.SubTotal);
      Console.WriteLine("\t\t\t\t\t Shipping\t" + po.ShipCost);
      Console.WriteLine("\t\t\t\t\t Total\t\t" + po.TotalCost);
   }

   protected void ReadAddress(Address a, string label)
   {
      // Read the fields of the Address object.
      Console.WriteLine(label);
      Console.WriteLine("\t"+ a.Name );
      Console.WriteLine("\t" + a.Line1);
      Console.WriteLine("\t" + a.City);
      Console.WriteLine("\t" + a.State);
      Console.WriteLine("\t" + a.Zip );
      Console.WriteLine();
   }

   private void serializer_UnknownNode
   (object sender, XmlNodeEventArgs e)
   {
      Console.WriteLine("Unknown Node:" +   e.Name + "\t" + e.Text);
   }

   private void serializer_UnknownAttribute
   (object sender, XmlAttributeEventArgs e)
   {
      System.Xml.XmlAttribute attr = e.Attr;
      Console.WriteLine("Unknown attribute " +
      attr.Name + "='" + attr.Value + "'");
   }
}

注解

有关此 API 的详细信息,请参阅 XmlSerializer 的补充 API 说明

构造函数

XmlSerializer()

初始化 XmlSerializer 类的新实例。

XmlSerializer(Type)

初始化 XmlSerializer 类的新实例,该类可以将指定类型的对象序列化为 XML 文档,也可以将 XML 文档反序列化为指定类型的对象。

XmlSerializer(Type, String)

初始化 XmlSerializer 类的新实例,该类可以将指定类型的对象序列化为 XML 文档,也可以将 XML 文档反序列化为指定类型的对象。 指定所有 XML 元素的默认命名空间。

XmlSerializer(Type, Type[])

初始化 XmlSerializer 类的新实例,该类可以将指定类型的对象序列化为 XML 文档,也可以将 XML 文档反序列化为指定类型的对象。 如果属性或字段返回一个数组,则 extraTypes 参数指定可插入到该数组的对象。

XmlSerializer(Type, XmlAttributeOverrides)

初始化 XmlSerializer 类的新实例,该类可以将指定类型的对象序列化为 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(Type, XmlRootAttribute)

初始化 XmlSerializer 类的新实例,该类可以将指定类型的对象序列化为 XML 文档,也可以将 XML 文档反序列化为指定类型的对象。 还可以指定作为 XML 根元素使用的类。

XmlSerializer(XmlTypeMapping)

使用将一个类型映射到另一个类型的对象来初始化 XmlSerializer 类的实例。

方法

CanDeserialize(XmlReader)

获取一个值,该值指示此 XmlSerializer 是否可以反序列化指定的 XML 文档。

CreateReader()

返回一个对象,该对象用于读取要进行序列化的 XML 文档。

CreateWriter()

当在派生类中重写时,返回用于序列化对象的编写器。

Deserialize(Stream)

反序列化指定 Stream 包含的 XML 文档。

Deserialize(TextReader)

反序列化指定 TextReader 包含的 XML 文档。

Deserialize(XmlReader)

反序列化指定 XmlReader 包含的 XML 文档。

Deserialize(XmlReader, String)

反序列化指定 XmlReader 和编码样式包含的 XML 文档。

Deserialize(XmlReader, String, XmlDeserializationEvents)

使用指定的 XmlReader 包含的数据反序列化该对象。

Deserialize(XmlReader, XmlDeserializationEvents)

反序列化一个由指定的 XmlReader 包含的 XML 文档,并允许重写反序列化过程中发生的事件。

Deserialize(XmlSerializationReader)

反序列化指定 XmlSerializationReader 包含的 XML 文档。

Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
FromMappings(XmlMapping[])

返回从 XmlSerializer 对象的数组创建的 XmlTypeMapping 对象的数组。

FromMappings(XmlMapping[], Evidence)
已过时.

返回 XmlSerializer 类的实例,该类通过一个 XML 类型到另一个 XML 类型的映射来创建。

FromMappings(XmlMapping[], Type)

从指定的映射返回 XmlSerializer 类的实例。

FromTypes(Type[])

返回从类型数组创建的 XmlSerializer 对象的数组。

GenerateSerializer(Type[], XmlMapping[])

使用指定映射返回一个程序集,该程序集包含的自定义序列化程序用于序列化或反序列化指定的一个或多个类型。

GenerateSerializer(Type[], XmlMapping[], CompilerParameters)

使用指定映射、编译器设置和选项返回一个程序集,该程序集包含的自定义序列化程序用于序列化或反序列化指定的一个或多个类型。

GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
GetXmlSerializerAssemblyName(Type)

返回程序集的名称,该程序集包含专门为序列化或反序列化特定类型创建的 XmlSerializer 的一个或多个版本。

GetXmlSerializerAssemblyName(Type, String)

返回程序集的名称,该程序集包含指定命名空间中指定类型的序列化程序。

MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
Serialize(Object, XmlSerializationWriter)

使用指定的 Object 序列化指定的 XmlSerializationWriter 并将 XML 文档写入文件。

Serialize(Stream, Object)

使用指定的 Object 序列化指定的 Stream 并将 XML 文档写入文件。

Serialize(Stream, Object, XmlSerializerNamespaces)

使用引用指定命名空间的指定 Stream 序列化指定的 Object 并将 XML 文档写入文件。

Serialize(TextWriter, Object)

使用指定的 Object 序列化指定的 TextWriter 并将 XML 文档写入文件。

Serialize(TextWriter, Object, XmlSerializerNamespaces)

使用指定的 Object 和指定命名空间序列化指定的 TextWriter 并将 XML 文档写入文件。

Serialize(XmlWriter, Object)

使用指定的 Object 序列化指定的 XmlWriter 并将 XML 文档写入文件。

Serialize(XmlWriter, Object, XmlSerializerNamespaces)

使用指定的 Object 和指定命名空间序列化指定的 XmlWriter 并将 XML 文档写入文件。

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String)

使用指定的 XmlWriter 和指定命名空间及编码样式序列化指定对象并将 XML 文档写入文件。

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String, String)

使用指定的 Object、XML 命名空间和编码序列化指定的 XmlWriter 并将 XML 文档写入文件。

ToString()

返回表示当前对象的字符串。

(继承自 Object)

事件

UnknownAttribute

XmlSerializer 在反序列化过程中遇到未知类型的 XML 特性时发生。

UnknownElement

XmlSerializer 在反序列化过程中遇到未知类型的 XML 元素时发生。

UnknownNode

XmlSerializer 在反序列化过程中遇到未知类型的 XML 节点时发生。

UnreferencedObject

在反序列化 SOAP 编码的 XML 流的过程中发生,此时 XmlSerializer 遇到未使用(或未引用)的识别类型。

适用于

产品 版本
.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, 8, 9
.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, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

线程安全性

此类型是线程安全的。

另请参阅