XmlSerializer 类

定义

将对象序列化和反序列化到 XML 文档和从 XML 文档反序列化对象。 这使 XmlSerializer 你能够控制如何将对象编码为 XML。

public ref class XmlSerializer
public class XmlSerializer
type XmlSerializer = class
Public Class XmlSerializer
继承
XmlSerializer

示例

以下示例包含两个主要类: 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 + "'");
   }
}
Imports System.Xml
Imports System.Xml.Serialization
Imports 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 ShipTo As Address
    Public OrderDate As String
    ' The XmlArrayAttribute changes the XML element name
    ' from the default of "OrderedItems" to "Items". 
    <XmlArrayAttribute("Items")> _
    Public OrderedItems() As OrderedItem
    Public SubTotal As Decimal
    Public ShipCost As Decimal
    Public TotalCost As Decimal
End Class


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 Name As String
    Public Line1 As String
    
    ' 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 City As String
    Public State As String
    Public Zip As String
End Class


Public Class OrderedItem
    Public ItemName As String
    Public Description As String
    Public UnitPrice As Decimal
    Public Quantity As Integer
    Public LineTotal As Decimal
    
    
    ' Calculate is a custom method that calculates the price per item,
    ' and stores the value in a field. 
    Public Sub Calculate()
        LineTotal = UnitPrice * Quantity
    End Sub
End Class


Public Class Test
    
   Public Shared Sub Main()
      ' Read and write purchase orders.
      Dim t As New Test()
      t.CreatePO("po.xml")
      t.ReadPO("po.xml")
   End Sub
    
   Private Sub CreatePO(filename As String)
      ' Create an instance of the XmlSerializer class;
      ' specify the type of object to serialize.
      Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
      Dim writer As New StreamWriter(filename)
      Dim po As New PurchaseOrder()
        
      ' Create an address to ship and bill to.
      Dim billAddress As 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.
      Dim i1 As New OrderedItem()
      i1.ItemName = "Widget S"
      i1.Description = "Small widget"
      i1.UnitPrice = CDec(5.23)
      i1.Quantity = 3
      i1.Calculate()
        
      ' Insert the item into the array.
      Dim items(0) As OrderedItem
      items(0) = i1
      po.OrderedItems = items
      ' Calculate the total cost.
      Dim subTotal As New Decimal()
      Dim oi As OrderedItem
      For Each oi In  items
         subTotal += oi.LineTotal
      Next oi
      po.SubTotal = subTotal
      po.ShipCost = CDec(12.51)
      po.TotalCost = po.SubTotal + po.ShipCost
      ' Serialize the purchase order, and close the TextWriter.
      serializer.Serialize(writer, po)
      writer.Close()
   End Sub
    
   Protected Sub ReadPO(filename As String)
      ' Create an instance of the XmlSerializer class;
      ' specify the type of object to be deserialized.
      Dim serializer As New XmlSerializer(GetType(PurchaseOrder))
      ' If the XML document has been altered with unknown
      ' nodes or attributes, handle them with the
      ' UnknownNode and UnknownAttribute events.
      AddHandler serializer.UnknownNode, AddressOf serializer_UnknownNode
      AddHandler serializer.UnknownAttribute, AddressOf serializer_UnknownAttribute
      
      ' A FileStream is needed to read the XML document.
      Dim fs As New FileStream(filename, FileMode.Open)
      ' Declare an object variable of the type to be deserialized.
      Dim po As PurchaseOrder
      ' Use the Deserialize method to restore the object's state with
      ' data from the XML document. 
      po = CType(serializer.Deserialize(fs), PurchaseOrder)
      ' Read the order date.
      Console.WriteLine(("OrderDate: " & po.OrderDate))
        
      ' Read the shipping address.
      Dim shipTo As Address = po.ShipTo
      ReadAddress(shipTo, "Ship To:")
      ' Read the list of ordered items.
      Dim items As OrderedItem() = po.OrderedItems
      Console.WriteLine("Items to be shipped:")
      Dim oi As OrderedItem
      For Each oi In  items
         Console.WriteLine((ControlChars.Tab & oi.ItemName & ControlChars.Tab & _
         oi.Description & ControlChars.Tab & oi.UnitPrice & ControlChars.Tab & _
         oi.Quantity & ControlChars.Tab & oi.LineTotal))
      Next oi
      ' Read the subtotal, shipping cost, and total cost.
      Console.WriteLine(( New String(ControlChars.Tab, 5) & _
      " Subtotal"  & ControlChars.Tab & po.SubTotal))
      Console.WriteLine(New String(ControlChars.Tab, 5) & _
      " Shipping" & ControlChars.Tab & po.ShipCost )
      Console.WriteLine( New String(ControlChars.Tab, 5) & _
      " Total" &  New String(ControlChars.Tab, 2) & po.TotalCost)
    End Sub
    
    Protected Sub ReadAddress(a As Address, label As String)
      ' Read the fields of the Address object.
      Console.WriteLine(label)
      Console.WriteLine(ControlChars.Tab & a.Name)
      Console.WriteLine(ControlChars.Tab & a.Line1)
      Console.WriteLine(ControlChars.Tab & a.City)
      Console.WriteLine(ControlChars.Tab & a.State)
      Console.WriteLine(ControlChars.Tab & a.Zip)
      Console.WriteLine()
    End Sub
        
    Private Sub serializer_UnknownNode(sender As Object, e As XmlNodeEventArgs)
        Console.WriteLine(("Unknown Node:" & e.Name & ControlChars.Tab & e.Text))
    End Sub
    
    
    Private Sub serializer_UnknownAttribute(sender As Object, e As XmlAttributeEventArgs)
        Dim attr As System.Xml.XmlAttribute = e.Attr
        Console.WriteLine(("Unknown attribute " & attr.Name & "='" & attr.Value & "'"))
    End Sub
End Class

注解

XML 序列化是将对象的公共属性和字段转换为存储或传输的串行格式(在本例中为 XML)的过程。 反序列化将 XML 输出中的对象还原到其原始状态。 可以将序列化视为将对象状态保存到流或缓冲区的方法。 例如,ASP.NET 使用该 XmlSerializer 类对 XML Web 服务消息进行编码。

使用编程语言结构(如类、字段、属性、基本类型、数组,甚至通过 XmlElementXmlAttribute 对象形式嵌入的 XML)描述对象中的数据。 可以选择创建自己的类、使用属性批注或使用 XML 架构定义工具(Xsd.exe) 基于现有 XML 架构定义(XSD)文档生成类。 如果您有一个 XML 架构,可以运行 Xsd.exe 命令来生成一组与该架构强类型匹配的类,并在序列化时用属性进行注释以遵循该架构。

若要在对象和 XML 之间传输数据,需要从编程语言构造到 XML 架构以及从 XML 架构到编程语言构造的映射。 XmlSerializerXsd.exe 等相关工具在设计时和运行时提供这两种技术之间的桥梁。 在设计时,使用 Xsd.exe 从自定义类生成 XML 架构文档(.xsd),或从给定架构生成类。 在任一情况下,类都使用自定义属性进行批注,以指示 XmlSerializer 如何在 XML 架构系统和公共语言运行时之间映射。 在运行时,类的实例可以序列化为遵循给定架构的 XML 文档。 同样,可以将这些 XML 文档反序列化为运行时对象。 请注意,XML 架构是可选的,在设计时或运行时不需要。

控制生成的 XML

若要控制生成的 XML,可以将特殊属性应用于类和成员。 例如,若要指定不同的 XML 元素名称,请向公共字段或属性应用一个 XmlElementAttribute ,并设置该 ElementName 属性。 有关类似属性的完整列表,请参阅 控制 XML 序列化的属性。 还可以实现 IXmlSerializable 接口来控制 XML 输出。

如果生成的 XML 必须符合万维网联合会文档简单对象访问协议 (SOAP) 1.1 第 5 节的内容,则必须使用 XmlSerializer 构造 XmlTypeMapping。 若要进一步控制编码的 SOAP XML,请使用 控制编码 SOAP 序列化的属性中列出的属性。

通过使用XmlSerializer,您可以充分利用强类型类的优势,同时仍然享有 XML 的灵活性。 使用强类型类中类型为 XmlElementXmlAttributeXmlNode 的字段或属性,可以直接将 XML 文档的某些部分读取到 XML 对象中。

如果使用可扩展 XML 架构,还可以使用 XmlAnyElementAttributeXmlAnyAttributeAttribute 属性对原始架构中未找到的元素或属性进行序列化和反序列化。 若要使用这些对象,请向返回XmlAnyElementAttribute对象数组的字段应用XmlElement,或向返回XmlAnyAttributeAttribute对象数组的字段应用XmlAttribute

如果属性或字段返回复杂对象(如数组或类实例),则 XmlSerializer 将其转换为嵌套在主 XML 文档中的元素。 例如,以下代码中的第一个类返回第二个类的实例。

Public Class MyClass
    Public MyObjectProperty As MyObject
End Class

Public Class MyObject
    Public ObjectName As String
End Class
public class MyClass
{
    public MyObject MyObjectProperty;
}
public class MyObject
{
    public string ObjectName;
}

序列化的 XML 输出如下所示:

<MyClass>
  <MyObjectProperty>
  <ObjectName>My String</ObjectName>
  </MyObjectProperty>
</MyClass>

如果架构包含可选元素(minOccurs = '0),或者架构包含默认值,则有两个选项。 一个选项是用于 System.ComponentModel.DefaultValueAttribute 指定默认值,如以下代码所示。

Public Class PurchaseOrder
    <System.ComponentModel.DefaultValueAttribute ("2002")> _
    Public Year As String
End Class
public class PurchaseOrder
{
    [System.ComponentModel.DefaultValueAttribute ("2002")]
    public string Year;
}

另一个选项是使用特殊模式创建布尔字段,该字段由 XmlSerializer 识别,并将 XmlIgnoreAttribute 应用于该字段。 模式以propertyNameSpecified的形式创建。 例如,如果有一个名为“MyFirstName”的字段,则还会创建一个名为“MyFirstNameSpecified”的字段,该 XmlSerializer 字段指示是否生成名为“MyFirstName”的 XML 元素。 下面的示例说明了这一点。

Public Class OptionalOrder
    ' This field's value should not be serialized
    ' if it is uninitialized.
    Public FirstOrder As String

    ' Use the XmlIgnoreAttribute to ignore the
    ' special field named "FirstOrderSpecified".
    <System.Xml.Serialization.XmlIgnoreAttribute> _
    Public FirstOrderSpecified As Boolean
End Class
public class OptionalOrder
{
    // This field should not be serialized
    // if it is uninitialized.
    public string FirstOrder;

    // Use the XmlIgnoreAttribute to ignore the
    // special field named "FirstOrderSpecified".
    [System.Xml.Serialization.XmlIgnoreAttribute]
    public bool FirstOrderSpecified;
}

覆盖默认序列化

还可以通过创建适当的属性之一并将其添加到类的实例 XmlAttributes 来替代任意一组对象的序列化及其字段和属性。 以这种方式重写序列化有两个用途:首先,可以控制和扩充 DLL 中找到的对象序列化,即使你无权访问源:其次,可以创建一组可序列化类,但以多种方式序列化对象。 有关更多详细信息,请参阅 XmlAttributeOverrides 类和 如何:控制派生类的序列化

若要序列化对象,请调用 Serialize 该方法。 若要反序列化对象,请调用 Deserialize 该方法。

若要向 XML 文档添加 XML 命名空间,请参阅 XmlSerializerNamespaces

注释

XmlSerializer 提供对实现 IEnumerableICollection 的类的特殊处理。 实现的 IEnumerable 类必须实现采用单个参数的公共 Add 方法。 Add 方法的参数的类型必须与从 Current 返回的值的 GetEnumerator 属性返回的类型或该类型的基之一相同。 除了 ICollection 之外,实现 CollectionBase(如 IEnumerable)的类还必须有一个采用整数的公共 Item 索引属性(在 C# 中为索引器),而且必须有一个整数类型的公共 Count 属性。 方法的参数 Add 必须与从 Item 属性返回的类型相同,或者从该类型的基类型之一返回。 对于实现 ICollection的类,要序列化的值是从索引 Item 属性中检索的,而不是通过调用 GetEnumerator

要反序列化一个对象,需要有写入临时目录(由 TEMP 环境变量定义)的权限。

动态生成的程序集

为了提高性能,XML 序列化基础结构动态生成程序集来序列化和反序列化指定的类型。 基础结构查找并重复使用这些程序集。 仅当使用以下构造函数时,才会发生此行为:

XmlSerializer.XmlSerializer(Type)

XmlSerializer.XmlSerializer(Type, String)

如果使用任何其他构造函数,则生成并永远不会卸载同一程序集的多个版本,这会导致内存泄漏和性能不佳。 最简单的解决方案是使用前面提到的两个构造函数之一。 否则,必须将程序集缓存到Hashtable中,如以下示例所示。

Hashtable serializers = new Hashtable();

// Use the constructor that takes a type and XmlRootAttribute.
XmlSerializer s = new XmlSerializer(typeof(MyClass), myRoot);

// Implement a method named GenerateKey that creates unique keys
// for each instance of the XmlSerializer. The code should take
// into account all parameters passed to the XmlSerializer
// constructor.
object key = GenerateKey(typeof(MyClass), myRoot);

// Check the local cache for a matching serializer.
XmlSerializer ser = (XmlSerializer)serializers[key];
if (ser == null)
{
    ser = new XmlSerializer(typeof(MyClass), myRoot);
    // Cache the serializer.
    serializers[key] = ser;
}

// Use the serializer to serialize or deserialize.
Dim serializers As New Hashtable()

' Use the constructor that takes a type and XmlRootAttribute.
Dim s As New XmlSerializer(GetType([MyClass]), myRoot)

' Implement a method named GenerateKey that creates unique keys
' for each instance of the XmlSerializer. The code should take
' into account all parameters passed to the XmlSerializer
' constructor.
Dim key As Object = GenerateKey(GetType([MyClass]), myRoot)

' Check the local cache for a matching serializer.
Dim ser As XmlSerializer = CType(serializers(key), XmlSerializer)

If ser Is Nothing Then
    ser = New XmlSerializer(GetType([MyClass]), myRoot)
    ' Cache the serializer.
    serializers(key) = ser
End If

' Use the serializer to serialize or deserialize.

ArrayList 和泛型列表的序列化

XmlSerializer 无法序列化或反序列化以下内容:

无符号 Long 枚举的序列化

XmlSerializer如果满足以下条件,则无法实例化以序列化枚举:枚举的类型为无符号长(ulong以 C# 为单位),并且枚举包含值大于 9,223,372,036,854,775,807 的任何成员。 例如,无法序列化以下内容。

public enum LargeNumbers: ulong
{
    a = 9223372036854775808
}
// At runtime, the following code will fail.
xmlSerializer mySerializer=new XmlSerializer(typeof(LargeNumbers));

过时类型

XmlSerializer 类不序列化标记为 [Obsolete]..

构造函数

名称 说明
XmlSerializer()

初始化 XmlSerializer 类的新实例。

XmlSerializer(Type, String)

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

XmlSerializer(Type, Type[])

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

XmlSerializer(Type, XmlAttributeOverrides, Type[], XmlRootAttribute, String, String, Evidence)
已过时.

初始化类的新实例,该实例 XmlSerializer 可以将指定类型的对象序列化为 XML 文档实例,并将 XML 文档实例反序列化为指定类型的对象。 通过此重载,可以提供可在序列化或反序列化操作期间遇到的其他类型的,以及所有 XML 元素的默认命名空间、用作 XML 根元素的类、其位置和访问所需的凭据。

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

初始化类的新实例,该实例 XmlSerializer 可将类型的 Object 对象序列化为 XML 文档实例,并将 XML 文档实例反序列化为类型 Object对象。 要序列化的每个对象本身可以包含类的实例,此重载将替代其他类。 此重载还指定用作 XML 根元素的所有 XML 元素和类的默认命名空间。

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

初始化类的新实例,该实例 XmlSerializer 可将类型的 Object 对象序列化为 XML 文档实例,并将 XML 文档实例反序列化为类型 Object对象。 要序列化的每个对象本身可以包含类的实例,此重载将替代其他类。 此重载还指定用作 XML 根元素的所有 XML 元素和类的默认命名空间。

XmlSerializer(Type, XmlAttributeOverrides)

初始化类的新实例,该实例 XmlSerializer 可将指定类型的对象序列化为 XML 文档,并将 XML 文档反序列化为指定类型的对象。 要序列化的每个对象本身可以包含类的实例,此重载可以与其他类替代这些实例。

XmlSerializer(Type, XmlRootAttribute)

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

XmlSerializer(Type)

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

XmlSerializer(XmlTypeMapping)

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

方法

名称 说明
CanDeserialize(XmlReader)

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

CreateReader()

返回用于读取要序列化的 XML 文档的对象。

CreateWriter()

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

Deserialize(Stream)

反序列化指定的 StreamXML 文档。

Deserialize(TextReader)

反序列化指定的 TextReaderXML 文档。

Deserialize(XmlReader, String, XmlDeserializationEvents)

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

Deserialize(XmlReader, String)

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

Deserialize(XmlReader, XmlDeserializationEvents)

反序列化指定的 XmlReader XML 文档,并允许重写反序列化期间发生的事件。

Deserialize(XmlReader)

反序列化指定的 XmlReaderXML 文档。

Deserialize(XmlSerializationReader)

反序列化指定的 XmlSerializationReaderXML 文档。

Equals(Object)

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

(继承自 Object)
FromMappings(XmlMapping[], Evidence)
已过时.

返回从一个 XML 类型映射到另一种 XML 类型的类的实例 XmlSerializer

FromMappings(XmlMapping[], Type)

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

FromMappings(XmlMapping[])

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

FromTypes(Type[])

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

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

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

GenerateSerializer(Type[], XmlMapping[])

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

GetHashCode()

用作默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
GetXmlSerializerAssemblyName(Type, String)

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

GetXmlSerializerAssemblyName(Type)

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

MemberwiseClone()

创建当前 Object的浅表副本。

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

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

Serialize(Stream, Object, XmlSerializerNamespaces)

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

Serialize(Stream, Object)

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

Serialize(TextWriter, Object, XmlSerializerNamespaces)

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

Serialize(TextWriter, Object)

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

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

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

Serialize(XmlWriter, Object, XmlSerializerNamespaces, String)

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

Serialize(XmlWriter, Object, XmlSerializerNamespaces)

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

Serialize(XmlWriter, Object)

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

ToString()

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

(继承自 Object)

活动

名称 说明
UnknownAttribute

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

UnknownElement

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

UnknownNode

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

UnreferencedObject

当遇到未使用或未引用的已识别类型时,在 SOAP 编码的 XML 流反序列化期间 XmlSerializer 发生。

适用于

线程安全性

此类型是线程安全的。

另请参阅