XmlSerializer XmlSerializer XmlSerializer XmlSerializer Class

定义

将对象序列化到 XML 文档中和从 XML 文档中反序列化对象。Serializes and deserializes objects into and from XML documents. XmlSerializer 使您得以控制如何将对象编码到 XML 中。The XmlSerializer enables you to control how objects are encoded into XML.

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

示例

下面的示例包含两个主要类:PurchaseOrderTestThe following example contains two main classes: PurchaseOrder and Test. PurchaseOrder类包含有关单个的采购信息。The PurchaseOrder class contains information about a single purchase. Test类包含创建采购订单,并读取创建的采购订单的方法。The Test class contains the methods that create the purchase order, and that read the created purchase order.

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

using namespace System;
using namespace System::Xml;
using namespace System::Xml::Serialization;
using namespace System::IO;
ref class Address;
ref class OrderedItem;

/* 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 ref class PurchaseOrder
{
public:
   Address^ ShipTo;
   String^ OrderDate;

   /* The XmlArrayAttribute changes the XML element name
       from the default of "OrderedItems" to "Items". */

   [XmlArrayAttribute("Items")]
   array<OrderedItem^>^OrderedItems;
   Decimal SubTotal;
   Decimal ShipCost;
   Decimal TotalCost;
};

public ref class Address
{
public:

   /* The XmlAttribute instructs the XmlSerializer to serialize the Name
         field as an XML attribute instead of an XML element (the default
         behavior). */

   [XmlAttributeAttribute]
   String^ Name;
   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)]
   String^ City;
   String^ State;
   String^ Zip;
};

public ref class OrderedItem
{
public:
   String^ ItemName;
   String^ Description;
   Decimal UnitPrice;
   int Quantity;
   Decimal LineTotal;

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

};

public ref class Test
{
public:
   static void main()
   {
      // Read and write purchase orders.
      Test^ t = gcnew 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 = gcnew XmlSerializer( PurchaseOrder::typeid );
      TextWriter^ writer = gcnew StreamWriter( filename );
      PurchaseOrder^ po = gcnew PurchaseOrder;

      // Create an address to ship and bill to.
      Address^ billAddress = gcnew 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 = gcnew 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.
      array<OrderedItem^>^items = {i1};
      po->OrderedItems = items;

      // Calculate the total cost.
      Decimal subTotal = Decimal(0);
      System::Collections::IEnumerator^ myEnum = items->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         OrderedItem^ oi = safe_cast<OrderedItem^>(myEnum->Current);
         subTotal = 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 = gcnew XmlSerializer( PurchaseOrder::typeid );

      /* If the XML document has been altered with unknown 
            nodes or attributes, handle them with the 
            UnknownNode and UnknownAttribute events.*/
      serializer->UnknownNode += gcnew XmlNodeEventHandler( this, &Test::serializer_UnknownNode );
      serializer->UnknownAttribute += gcnew XmlAttributeEventHandler( this, &Test::serializer_UnknownAttribute );

      // A FileStream is needed to read the XML document.
      FileStream^ fs = gcnew 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 = dynamic_cast<PurchaseOrder^>(serializer->Deserialize( fs ));

      // Read the order date.
      Console::WriteLine( "OrderDate: {0}", po->OrderDate );

      // Read the shipping address.
      Address^ shipTo = po->ShipTo;
      ReadAddress( shipTo, "Ship To:" );

      // Read the list of ordered items.
      array<OrderedItem^>^items = po->OrderedItems;
      Console::WriteLine( "Items to be shipped:" );
      System::Collections::IEnumerator^ myEnum1 = items->GetEnumerator();
      while ( myEnum1->MoveNext() )
      {
         OrderedItem^ oi = safe_cast<OrderedItem^>(myEnum1->Current);
         Console::WriteLine( "\t{0}\t{1}\t{2}\t{3}\t{4}", oi->ItemName, oi->Description, oi->UnitPrice, oi->Quantity, oi->LineTotal );
      }

      Console::WriteLine( "\t\t\t\t\t Subtotal\t{0}", po->SubTotal );
      Console::WriteLine( "\t\t\t\t\t Shipping\t{0}", po->ShipCost );
      Console::WriteLine( "\t\t\t\t\t Total\t\t{0}", po->TotalCost );
   }

   void ReadAddress( Address^ a, String^ label )
   {
      // Read the fields of the Address object.
      Console::WriteLine( label );
      Console::WriteLine( "\t{0}", a->Name );
      Console::WriteLine( "\t{0}", a->Line1 );
      Console::WriteLine( "\t{0}", a->City );
      Console::WriteLine( "\t{0}", a->State );
      Console::WriteLine( "\t{0}", a->Zip );
      Console::WriteLine();
   }

private:
   void serializer_UnknownNode( Object^ /*sender*/, XmlNodeEventArgs^ e )
   {
      Console::WriteLine( "Unknown Node:{0}\t{1}", e->Name, e->Text );
   }

   void serializer_UnknownAttribute( Object^ /*sender*/, XmlAttributeEventArgs^ e )
   {
      System::Xml::XmlAttribute^ attr = e->Attr;
      Console::WriteLine( "Unknown attribute {0}='{1}'", attr->Name, attr->Value );
   }
};

int main()
{
   Test::main();
}
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
Imports System.Xml
Imports System.Xml.Serialization
Imports System.IO
Imports Microsoft.VisualBasic


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


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


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 'Calculate
End Class 'OrderedItem


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 'Main
    
   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 'CreatePO
    
   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 'ReadPO
    
    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 'ReadAddress
        
    Private Sub serializer_UnknownNode(sender As Object, e As XmlNodeEventArgs)
        Console.WriteLine(("Unknown Node:" & e.Name & ControlChars.Tab & e.Text))
    End Sub 'serializer_UnknownNode
    
    
    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 'serializer_UnknownAttribute
End Class 'Test

注解

XML 序列化是将对象的公共属性和字段转换为序列格式(这里是指 XML)以便存储或传输的过程。XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. 反序列化重新创建中的 XML 输出从其原始状态的对象。Deserialization re-creates the object in its original state from the XML output. 您可以将序列化对象的状态保存到流或缓冲区的方式。You can think of serialization as a way of saving the state of an object into a stream or buffer. 例如,ASP.NET 使用XmlSerializer类 XML Web 服务消息进行编码。For example, ASP.NET uses the XmlSerializer class to encode XML Web service messages.

对象中的数据是用编程语言构造来描述的,如类、字段、属性、基元类型、数组,甚至 XmlElementXmlAttribute 对象形式的嵌入 XML。The data in your objects is described using programming language constructs like classes, fields, properties, primitive types, arrays, and even embedded XML in the form of XmlElement or XmlAttribute objects. 您可以创建您自己的类,使用属性,或使用批注XML 架构定义工具 (Xsd.exe)生成基于现有 XML 架构定义 (XSD) 文档的类。You have the option of creating your own classes, annotated with attributes, or using the XML Schema Definition Tool (Xsd.exe) to generate the classes based on an existing XML Schema definition (XSD) document. 如果您有一个 XML 架构,可以运行 Xsd.exe 生成一组强类型化为架构并使用要遵守架构时序列化属性批注的类。If you have an XML Schema, you can run the Xsd.exe to produce a set of classes that are strongly typed to the schema and annotated with attributes to adhere to the schema when serialized.

若要将数据传输对象和 XML 之间,需要从 XML 架构的编程语言构造和编程语言构造的 XML 架构的映射。To transfer data between objects and XML requires a mapping from the programming language constructs to XML schema and from the XML schema to the programming language constructs. XmlSerializer和 Xsd.exe 等相关的工具提供这两种技术在同时设计时和运行时之间的桥梁。The XmlSerializer and related tools like Xsd.exe provide the bridge between these two technologies at both design time and runtime. 在设计时,使用 Xsd.exe 从自定义类生成 XML 架构文档 (.xsd) 或生成给定架构中的类。At design time, use the Xsd.exe to produce an XML schema document (.xsd) from your custom classes or to produce classes from a given schema. 在任一情况下,这些类进行批注和自定义特性来指示XmlSerializer如何以 XML 架构系统和公共语言运行时之间进行映射。In either case, the classes are annotated with custom attributes to instruct the XmlSerializer how to map between the XML schema system and the common language runtime. 在运行时,这些类的实例可以序列化为 XML 文档,请按照给定的架构。At runtime, instances of the classes can be serialized into XML documents that follow the given schema. 同样,可以将这些 XML 文档反序列化到运行时对象中。Likewise, these XML documents can be deserialized into runtime objects. 请注意,XML 架构是可选的在设计时或运行时并不是必需的。Note that the XML schema is optional, and not required at design time or runtime.

控制生成的 XMLControlling Generated XML

若要控制生成的 XML,可以将特殊特性应用于类和成员中。To control the generated XML, you can apply special attributes to classes and members. 例如,若要指定不同的 XML 元素名称,请应用XmlElementAttribute公共字段或属性,以及组ElementName属性。For example, to specify a different XML element name, apply an XmlElementAttribute to a public field or property, and set the ElementName property. 有关类似属性的完整列表,请参阅Attributes That Control XML SerializationFor a complete list of similar attributes, see Attributes That Control XML Serialization. 您还可以实现IXmlSerializable界面,用于控制 XML 输出。You can also implement the IXmlSerializable interface to control the XML output.

如果生成的 XML 必须符合万维网联合会文档的第 5 节简单对象访问协议 (SOAP) 1.1,必须构造XmlSerializerXmlTypeMappingIf the XML generated must conform to section 5 of the World Wide Consortium document, Simple Object Access Protocol (SOAP) 1.1, you must construct the XmlSerializer with an XmlTypeMapping. 若要进一步控制编码的 SOAP XML,请使用中列出的特性属性 That Control Encoded SOAP SerializationTo further control the encoded SOAP XML, use the attributes listed in Attributes That Control Encoded SOAP Serialization.

使用XmlSerializer可以充分利用使用强类型化类并仍有 XML 的灵活性。With the XmlSerializer you can take advantage of working with strongly typed classes and still have the flexibility of XML. 使用类型的字段或属性XmlElementXmlAttributeXmlNode中强类型化的类,可以直接在 XML 对象读取 XML 文档的各个部分。Using fields or properties of type XmlElement, XmlAttribute or XmlNode in your strongly typed classes, you can read parts of the XML document directly into XML objects.

如果您使用扩展的 XML 架构,还可以使用XmlAnyElementAttributeXmlAnyAttributeAttribute属性进行序列化和反序列化的原始架构中找不到元素或属性。If you work with extensible XML schemas, you can also use the XmlAnyElementAttribute and XmlAnyAttributeAttribute attributes to serialize and deserialize elements or attributes that are not found in the original schema. 若要使用的对象,将应用XmlAnyElementAttribute返回的数组的字段XmlElement对象,或将应用XmlAnyAttributeAttribute返回的数组的字段XmlAttribute对象。To use the objects, apply an XmlAnyElementAttribute to a field that returns an array of XmlElement objects, or apply an XmlAnyAttributeAttribute to a field that returns an array of XmlAttribute objects.

如果属性或字段返回一个复杂对象(如数组或类实例),则 XmlSerializer 将其转换为嵌套在主 XML 文档内的元素。If a property or field returns a complex object (such as an array or a class instance), the XmlSerializer converts it to an element nested within the main XML document. 例如,下面的代码中的第一个类返回第二个类的实例。For example, the first class in the following code returns an instance of the second class.

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 输出如下所示:The serialized, XML output looks like this:

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

如果架构包含的元素是可选的 (minOccurs ="0"),或如果该架构包含默认值,有两个选项。If a schema includes an element that is optional (minOccurs = '0'), or if the schema includes a default value, you have two options. 一种选择是使用System.ComponentModel.DefaultValueAttribute指定默认值,如下面的代码中所示。One option is to use System.ComponentModel.DefaultValueAttribute to specify the default value, as shown in the following code.

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的字段。Another option is to use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. 中的窗体创建模式propertyNameSpecifiedThe pattern is created in the form of propertyNameSpecified. 例如,如果没有名为"MyFirstName"也会创建一个名为"MyFirstNameSpecified"字段的字段指示XmlSerializer是否生成名为"MyFirstName"的 XML 元素。For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the XmlSerializer whether to generate the XML element named "MyFirstName". 这在下面的示例中显示。This is shown in the following example.

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

重写默认序列化Overriding Default Serialization

你也可以通过创建一个适当的属性,并将其添加到的实例替代的序列化的对象和其字段和属性的任何一组XmlAttributes类。You can also override the serialization of any set of objects and their fields and properties by creating one of the appropriate attributes, and adding it to an instance of the XmlAttributes class. 重写以这种方式序列化有两个用途: 首先,您可以控制和增强的 DLL 中找到的对象的序列化,即使到源,则不能访问第二,您可以创建一组可序列化类,但序列化多个方法中的对象。Overriding serialization in this way has two uses: first, you can control and augment the serialization of objects found in a DLL, even if you do not have access to the source; second, you can create one set of serializable classes, but serialize the objects in multiple ways. 有关更多详细信息,请参阅XmlAttributeOverrides类和如何:控制派生类的序列化For more details, see the XmlAttributeOverrides class and How to: Control Serialization of Derived Classes.

若要序列化对象,调用Serialize方法。To serialize an object, call the Serialize method. 若要反序列化对象,调用Deserialize方法。To deserialize an object, call the Deserialize method.

若要将 XML 命名空间添加到 XML 文档,请参阅XmlSerializerNamespacesTo add XML namespaces to an XML document, see XmlSerializerNamespaces.

备注

XmlSerializer提供了到实现类的特殊处理方式IEnumerableICollectionThe XmlSerializer gives special treatment to classes that implement IEnumerable or ICollection. 实现 IEnumerable 的类必须实现采用单个参数的公共 Add 方法。A class that implements IEnumerable must implement a public Add method that takes a single parameter. Add方法的参数必须是相同类型的返回从Current属性返回的值GetEnumerator,或该类型的基之一。The Add method's parameter must be of the same type as is returned from the Current property on the value returned from GetEnumerator, or one of that type's bases. 实现的类ICollection(如CollectionBase) 除了IEnumerable必须具有一个公共Item索引属性 (C# 中的索引器) 采用一个整数,并且它必须具有公共Count整数类型属性。A class that implements ICollection (such as CollectionBase) in addition to IEnumerable must have a public Item indexed property (indexer in C#) that takes an integer, and it must have a public Count property of type integer. 参数Add方法必须是同一类型,从返回Item属性,或该类型的基之一。The parameter to the Add method must be the same type as is returned from the Item property, or one of that type's bases. 为类实现ICollection,要检索的值以进行序列化从已编制索引Item属性,不是通过调用GetEnumeratorFor classes that implement ICollection, values to be serialized are retrieved from the indexed Item property, not by calling GetEnumerator.

您必须有权写入到临时目录 (如由 TEMP 环境变量所定义) 来反序列化对象。You must have permission to write to the temporary directory (as defined by the TEMP environment variable) to deserialize an object.

动态生成的程序集Dynamically Generated Assemblies

若要提高性能,XML 序列化基础结构动态生成要序列化和反序列化指定的类型的程序集。To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types. 基础结构找到并重新使用这些程序集。The infrastructure finds and reuses those assemblies. 仅当使用以下构造函数时,会发生此行为:This behavior occurs only when using the following constructors:

XmlSerializer.XmlSerializer(Type)

XmlSerializer.XmlSerializer(Type, String)

如果使用任何其他构造函数,在同一程序集中的多个版本生成,并永远不会卸载,这会导致内存泄漏和性能不佳。If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. 最简单的解决方案是使用前面提到的两个构造函数之一。The easiest solution is to use one of the previously mentioned two constructors. 否则,你必须缓存中的程序集Hashtable,如以下示例所示。Otherwise, you must cache the assemblies in a Hashtable, as shown in the following example.

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 和泛型列表的序列化Serialization of ArrayList and Generic List

XmlSerializer无法序列化或反序列化以下:The XmlSerializer cannot serialize or deserialize the following:

无符号长整型的枚举的序列化Serialization of Enumerations of Unsigned Long

XmlSerializer不能实例化进行序列化一个枚举,如果满足以下条件:枚举是无符号长整型 (ulong在C#) 和该枚举包含的值大于 9,223,372,036,854,775,807 具有任何成员。The XmlSerializer cannot be instantiated to serialize an enumeration if the following conditions are true: The enumeration is of type unsigned long (ulong in C#) and the enumeration contains any member with a value larger than 9,223,372,036,854,775,807. 例如,以下无法序列化。For example, the following cannot be serialized.

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

标记为已过时的属性不能再进行序列化的对象Objects marked with the Obsolete Attribute no longer serialized

在中.NET Framework 3.5.NET Framework 3.5XmlSerializer类不能再将对象标记为序列化[Obsolete]In the .NET Framework 3.5.NET Framework 3.5 the XmlSerializer class no longer serializes objects that are marked as [Obsolete].

构造函数

XmlSerializer() XmlSerializer() XmlSerializer() XmlSerializer()

初始化 XmlSerializer 类的新实例。Initializes a new instance of the XmlSerializer class.

XmlSerializer(Type) XmlSerializer(Type) XmlSerializer(Type) XmlSerializer(Type)

初始化 XmlSerializer 类的新实例,该类可以将指定类型的对象序列化为 XML 文档,也可以将 XML 文档反序列化为指定类型的对象。Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type.

XmlSerializer(Type, String) XmlSerializer(Type, String) XmlSerializer(Type, String) XmlSerializer(Type, String)

初始化 XmlSerializer 类的新实例,该类可以将指定类型的对象序列化为 XML 文档,也可以将 XML 文档反序列化为指定类型的对象。Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type. 指定所有 XML 元素的默认命名空间。Specifies the default namespace for all the XML elements.

XmlSerializer(Type, Type[]) XmlSerializer(Type, Type[]) XmlSerializer(Type, Type[]) XmlSerializer(Type, Type[])

初始化 XmlSerializer 类的新实例,该类可以将指定类型的对象序列化为 XML 文档,也可以将 XML 文档反序列化为指定类型的对象。Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into object of a specified type. 如果属性或字段返回一个数组,则 extraTypes 参数指定可插入到该数组的对象。If a property or field returns an array, the extraTypes parameter specifies objects that can be inserted into the array.

XmlSerializer(Type, XmlAttributeOverrides) XmlSerializer(Type, XmlAttributeOverrides) XmlSerializer(Type, XmlAttributeOverrides) XmlSerializer(Type, XmlAttributeOverrides)

初始化 XmlSerializer 类的新实例,该类可以将指定类型的对象序列化为 XML 文档,也可以将 XML 文档反序列化为指定类型的对象。Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize XML documents into objects of the specified type. 要序列化的每个对象本身可包含类的实例,此重载可使用其他类重写这些实例。Each object to be serialized can itself contain instances of classes, which this overload can override with other classes.

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

初始化 XmlSerializer 类的新实例,该类可将 Object 类型的对象序列化为 XML 文档实例,并可将 XML 文档实例反序列化为 Object 类型的对象。Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances, and deserialize XML document instances into objects of type Object. 要序列化的每个对象本身可包含类的实例,此重载可使用其他类重写这些实例。Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. 此重载还指定所有 XML 元素的默认命名空间和用作 XML 根元素的类。This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.

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

初始化 XmlSerializer 类的新实例,该类可将 Object 类型的对象序列化为 XML 文档实例,并可将 XML 文档实例反序列化为 Object 类型的对象。Initializes a new instance of the XmlSerializer class that can serialize objects of type Object into XML document instances, and deserialize XML document instances into objects of type Object. 要序列化的每个对象本身可包含类的实例,此重载可使用其他类重写这些实例。Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. 此重载还指定所有 XML 元素的默认命名空间和用作 XML 根元素的类。This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.

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

初始化 XmlSerializer 类的新实例,该类可以将指定类型的对象序列化为 XML 文档,也可以将 XML 文档反序列化为指定类型的对象。Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML document instances, and deserialize XML document instances into objects of the specified type. 此重载允许您提供在序列化或反序列化操作过程中可能遇到的其他类型;还允许您提供所有 XML 元素的默认命名空间,作为 XML 根元素使用的类,类的位置和访问所需的凭据。This overload allows you to supply other types that can be encountered during a serialization or deserialization operation, as well as a default namespace for all XML elements, the class to use as the XML root element, its location, and credentials required for access.

XmlSerializer(Type, XmlRootAttribute) XmlSerializer(Type, XmlRootAttribute) XmlSerializer(Type, XmlRootAttribute) XmlSerializer(Type, XmlRootAttribute)

初始化 XmlSerializer 类的新实例,该类可以将指定类型的对象序列化为 XML 文档,也可以将 XML 文档反序列化为指定类型的对象。Initializes a new instance of the XmlSerializer class that can serialize objects of the specified type into XML documents, and deserialize an XML document into object of the specified type. 还可以指定作为 XML 根元素使用的类。It also specifies the class to use as the XML root element.

XmlSerializer(XmlTypeMapping) XmlSerializer(XmlTypeMapping) XmlSerializer(XmlTypeMapping) XmlSerializer(XmlTypeMapping)

使用将一个类型映射到另一个类型的对象来初始化 XmlSerializer 类的实例。Initializes an instance of the XmlSerializer class using an object that maps one type to another.

方法

CanDeserialize(XmlReader) CanDeserialize(XmlReader) CanDeserialize(XmlReader) CanDeserialize(XmlReader)

获取一个值,该值指示此 XmlSerializer 是否可以反序列化指定的 XML 文档。Gets a value that indicates whether this XmlSerializer can deserialize a specified XML document.

CreateReader() CreateReader() CreateReader() CreateReader()

返回一个对象,该对象用于读取要进行序列化的 XML 文档。Returns an object used to read the XML document to be serialized.

CreateWriter() CreateWriter() CreateWriter() CreateWriter()

当在派生类中重写时,返回用于序列化对象的编写器。When overridden in a derived class, returns a writer used to serialize the object.

Deserialize(Stream) Deserialize(Stream) Deserialize(Stream) Deserialize(Stream)

反序列化指定 Stream 包含的 XML 文档。Deserializes the XML document contained by the specified Stream.

Deserialize(TextReader) Deserialize(TextReader) Deserialize(TextReader) Deserialize(TextReader)

反序列化指定 TextReader 包含的 XML 文档。Deserializes the XML document contained by the specified TextReader.

Deserialize(XmlReader) Deserialize(XmlReader) Deserialize(XmlReader) Deserialize(XmlReader)

反序列化指定 XmlReader 包含的 XML 文档。Deserializes the XML document contained by the specified XmlReader.

Deserialize(XmlReader, String) Deserialize(XmlReader, String) Deserialize(XmlReader, String) Deserialize(XmlReader, String)

反序列化指定 XmlReader 和编码样式包含的 XML 文档。Deserializes the XML document contained by the specified XmlReader and encoding style.

Deserialize(XmlReader, String, XmlDeserializationEvents) Deserialize(XmlReader, String, XmlDeserializationEvents) Deserialize(XmlReader, String, XmlDeserializationEvents) Deserialize(XmlReader, String, XmlDeserializationEvents)

使用指定的 XmlReader 包含的数据反序列化该对象。Deserializes the object using the data contained by the specified XmlReader.

Deserialize(XmlReader, XmlDeserializationEvents) Deserialize(XmlReader, XmlDeserializationEvents) Deserialize(XmlReader, XmlDeserializationEvents) Deserialize(XmlReader, XmlDeserializationEvents)

反序列化一个由指定的 XmlReader 包含的 XML 文档,并允许重写反序列化过程中发生的事件。Deserializes an XML document contained by the specified XmlReader and allows the overriding of events that occur during deserialization.

Deserialize(XmlSerializationReader) Deserialize(XmlSerializationReader) Deserialize(XmlSerializationReader) Deserialize(XmlSerializationReader)

反序列化指定 XmlSerializationReader 包含的 XML 文档。Deserializes the XML document contained by the specified XmlSerializationReader.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
FromMappings(XmlMapping[]) FromMappings(XmlMapping[]) FromMappings(XmlMapping[]) FromMappings(XmlMapping[])

返回从 XmlSerializer 对象的数组创建的 XmlTypeMapping 对象的数组。Returns an array of XmlSerializer objects created from an array of XmlTypeMapping objects.

FromMappings(XmlMapping[], Evidence) FromMappings(XmlMapping[], Evidence) FromMappings(XmlMapping[], Evidence) FromMappings(XmlMapping[], Evidence)

返回 XmlSerializer 类的实例,该类通过一个 XML 类型到另一个 XML 类型的映射来创建。Returns an instance of the XmlSerializer class created from mappings of one XML type to another.

FromMappings(XmlMapping[], Type) FromMappings(XmlMapping[], Type) FromMappings(XmlMapping[], Type) FromMappings(XmlMapping[], Type)

从指定的映射返回 XmlSerializer 类的实例。Returns an instance of the XmlSerializer class from the specified mappings.

FromTypes(Type[]) FromTypes(Type[]) FromTypes(Type[]) FromTypes(Type[])

返回从类型数组创建的 XmlSerializer 对象的数组。Returns an array of XmlSerializer objects created from an array of types.

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

使用指定映射返回一个程序集,该程序集包含的自定义序列化程序用于序列化或反序列化指定的一个或多个类型。Returns an assembly that contains custom-made serializers used to serialize or deserialize the specified type or types, using the specified mappings.

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

使用指定映射、编译器设置和选项返回一个程序集,该程序集包含的自定义序列化程序用于序列化或反序列化指定的一个或多个类型。Returns an assembly that contains custom-made serializers used to serialize or deserialize the specified type or types, using the specified mappings and compiler settings and options.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
GetXmlSerializerAssemblyName(Type) GetXmlSerializerAssemblyName(Type) GetXmlSerializerAssemblyName(Type) GetXmlSerializerAssemblyName(Type)

返回程序集的名称,该程序集包含专门为序列化或反序列化特定类型创建的 XmlSerializer 的一个或多个版本。Returns the name of the assembly that contains one or more versions of the XmlSerializer especially created to serialize or deserialize the specified type.

GetXmlSerializerAssemblyName(Type, String) GetXmlSerializerAssemblyName(Type, String) GetXmlSerializerAssemblyName(Type, String) GetXmlSerializerAssemblyName(Type, String)

返回程序集的名称,该程序集包含指定命名空间中指定类型的序列化程序。Returns the name of the assembly that contains the serializer for the specified type in the specified namespace.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
Serialize(Object, XmlSerializationWriter) Serialize(Object, XmlSerializationWriter) Serialize(Object, XmlSerializationWriter) Serialize(Object, XmlSerializationWriter)

使用指定的 Object 序列化指定的 XmlSerializationWriter 并将 XML 文档写入文件。Serializes the specified Object and writes the XML document to a file using the specified XmlSerializationWriter.

Serialize(Stream, Object) Serialize(Stream, Object) Serialize(Stream, Object) Serialize(Stream, Object)

使用指定的 Object 序列化指定的 Stream 并将 XML 文档写入文件。Serializes the specified Object and writes the XML document to a file using the specified Stream.

Serialize(Stream, Object, XmlSerializerNamespaces) Serialize(Stream, Object, XmlSerializerNamespaces) Serialize(Stream, Object, XmlSerializerNamespaces) Serialize(Stream, Object, XmlSerializerNamespaces)

使用引用指定命名空间的指定 Stream 序列化指定的 Object 并将 XML 文档写入文件。Serializes the specified Object and writes the XML document to a file using the specified Stream that references the specified namespaces.

Serialize(TextWriter, Object) Serialize(TextWriter, Object) Serialize(TextWriter, Object) Serialize(TextWriter, Object)

使用指定的 Object 序列化指定的 TextWriter 并将 XML 文档写入文件。Serializes the specified Object and writes the XML document to a file using the specified TextWriter.

Serialize(TextWriter, Object, XmlSerializerNamespaces) Serialize(TextWriter, Object, XmlSerializerNamespaces) Serialize(TextWriter, Object, XmlSerializerNamespaces) Serialize(TextWriter, Object, XmlSerializerNamespaces)

使用指定的 Object 和指定命名空间序列化指定的 TextWriter 并将 XML 文档写入文件。Serializes the specified Object and writes the XML document to a file using the specified TextWriter and references the specified namespaces.

Serialize(XmlWriter, Object) Serialize(XmlWriter, Object) Serialize(XmlWriter, Object) Serialize(XmlWriter, Object)

使用指定的 Object 序列化指定的 XmlWriter 并将 XML 文档写入文件。Serializes the specified Object and writes the XML document to a file using the specified XmlWriter.

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

使用指定的 Object 和指定命名空间序列化指定的 XmlWriter 并将 XML 文档写入文件。Serializes the specified Object and writes the XML document to a file using the specified XmlWriter and references the specified namespaces.

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

使用指定的 XmlWriter 和指定命名空间及编码样式序列化指定对象并将 XML 文档写入文件。Serializes the specified object and writes the XML document to a file using the specified XmlWriter and references the specified namespaces and encoding style.

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

使用指定的 Object、XML 命名空间和编码序列化指定的 XmlWriter 并将 XML 文档写入文件。Serializes the specified Object and writes the XML document to a file using the specified XmlWriter, XML namespaces, and encoding.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

事件

UnknownAttribute UnknownAttribute UnknownAttribute UnknownAttribute

XmlSerializer 在反序列化过程中遇到未知类型的 XML 特性时发生。Occurs when the XmlSerializer encounters an XML attribute of unknown type during deserialization.

UnknownElement UnknownElement UnknownElement UnknownElement

XmlSerializer 在反序列化过程中遇到未知类型的 XML 元素时发生。Occurs when the XmlSerializer encounters an XML element of unknown type during deserialization.

UnknownNode UnknownNode UnknownNode UnknownNode

XmlSerializer 在反序列化过程中遇到未知类型的 XML 节点时发生。Occurs when the XmlSerializer encounters an XML node of unknown type during deserialization.

UnreferencedObject UnreferencedObject UnreferencedObject UnreferencedObject

在反序列化 SOAP 编码的 XML 流的过程中发生,此时 XmlSerializer 遇到未使用(或未引用)的识别类型。Occurs during deserialization of a SOAP-encoded XML stream, when the XmlSerializer encounters a recognized type that is not used or is unreferenced.

适用于

线程安全性

此类型是线程安全的。This type is thread safe.

另请参阅