NetDataContractSerializer 类

定义

使用提供的 .NET Framework 类型,将类型实例序列化和反序列化为 XML 流或文档。 此类不能被继承。

public ref class NetDataContractSerializer sealed : System::Runtime::Serialization::XmlObjectSerializer, System::Runtime::Serialization::IFormatter
public sealed class NetDataContractSerializer : System.Runtime.Serialization.XmlObjectSerializer, System.Runtime.Serialization.IFormatter
type NetDataContractSerializer = class
    inherit XmlObjectSerializer
    interface IFormatter
Public NotInheritable Class NetDataContractSerializer
Inherits XmlObjectSerializer
Implements IFormatter
继承
NetDataContractSerializer
实现

示例

下面的示例代码演示一种名为 Person 且由 NetDataContractSerializer 序列化的类型。 它将 DataContractAttribute 特性应用于类,并将 DataMemberAttribute 应用于成员(包括私有成员)以指示 NetDataContractSerializer 要序列化的内容。

// You must apply a DataContractAttribute or SerializableAttribute
// to a class to have it serialized by the NetDataContractSerializer.
[DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
class Person : IExtensibleDataObject
{
    [DataMember()]
    public string FirstName;
    [DataMember]
    public string LastName;
    [DataMember()]
    public int ID;

    public Person(string newfName, string newLName, int newID)
    {
        FirstName = newfName;
        LastName = newLName;
        ID = newID;
    }

    private ExtensionDataObject extensionData_Value;

    public ExtensionDataObject ExtensionData
    {
        get
        {
            return extensionData_Value;
        }
        set
        {
            extensionData_Value = value;
        }
    }
}

public sealed class Test
{
    private Test() { }

    public static void Main()
    {
        try
        {
            WriteObject("NetDataContractSerializerExample.xml");
            ReadObject("NetDataContractSerializerExample.xml");
        }

        catch (SerializationException serExc)
        {
            Console.WriteLine("Serialization Failed");
            Console.WriteLine(serExc.Message);
        }
        catch (Exception exc)
        {
            Console.WriteLine(
            "The serialization operation failed: {0} StackTrace: {1}",
            exc.Message, exc.StackTrace);
        }

        finally
        {
            Console.WriteLine("Press <Enter> to exit....");
            Console.ReadLine();
        }
    }

    public static void WriteObject(string fileName)
    {
        Console.WriteLine(
            "Creating a Person object and serializing it.");
        Person p1 = new Person("Zighetti", "Barbara", 101);
        FileStream fs = new FileStream(fileName, FileMode.Create);
        XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
        NetDataContractSerializer ser =
            new NetDataContractSerializer();
        ser.WriteObject(writer, p1);
        writer.Close();
    }

    public static void ReadObject(string fileName)
    {
        Console.WriteLine("Deserializing an instance of the object.");
        FileStream fs = new FileStream(fileName,
        FileMode.Open);
        XmlDictionaryReader reader =
            XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
        NetDataContractSerializer ser = new NetDataContractSerializer();

        // Deserialize the data and read it from the instance.
        Person deserializedPerson =
            (Person)ser.ReadObject(reader, true);
        fs.Close();
        Console.WriteLine(String.Format("{0} {1}, ID: {2}",
        deserializedPerson.FirstName, deserializedPerson.LastName,
        deserializedPerson.ID));
    }
}
' You must apply a DataContractAttribute or SerializableAttribute
' to a class to have it serialized by the NetDataContractSerializer.
<DataContract(Name := "Customer", [Namespace] := "http://www.contoso.com")>  _
Class Person
    Implements IExtensibleDataObject
    <DataMember()>  _
    Public FirstName As String
    <DataMember()>  _
    Public LastName As String
    <DataMember()>  _
    Public ID As Integer
    
    
    Public Sub New(ByVal newfName As String, ByVal newLName As String, _
       ByVal newID As Integer) 
        FirstName = newfName
        LastName = newLName
        ID = newID
    
    End Sub 
    
    Private extensionData_Value As ExtensionDataObject
    
    
    Public Property ExtensionData() As ExtensionDataObject _
     Implements IExtensibleDataObject.ExtensionData
        Get
            Return extensionData_Value
        End Get
        Set
            extensionData_Value = value
        End Set
    End Property
End Class 


NotInheritable Public Class Test

    Private Sub New() 
    
    End Sub
     
    Public Shared Sub Main() 
        Try
            WriteObject("NetDataContractSerializerExample.xml")
            ReadObject("NetDataContractSerializerExample.xml")
        
        Catch serExc As SerializationException
            Console.WriteLine("Serialization Failed")
            Console.WriteLine(serExc.Message)
        Catch exc As Exception
            Console.WriteLine("The serialization operation failed: {0} StackTrace: {1}", exc.Message, exc.StackTrace)
        
        Finally
            Console.WriteLine("Press <Enter> to exit....")
            Console.ReadLine()
        End Try
    
    End Sub 
    
    
    Public Shared Sub WriteObject(ByVal fileName As String) 
        Console.WriteLine("Creating a Person object and serializing it.")
        Dim p1 As New Person("Zighetti", "Barbara", 101)
        Dim fs As New FileStream(fileName, FileMode.Create)
        Dim writer As XmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(fs)
        Dim ser As New System.Runtime.Serialization.NetDataContractSerializer()

        ser.WriteObject(writer, p1)
        writer.Close()
    
    End Sub     

    Public Shared Sub ReadObject(ByVal fileName As String) 
        Console.WriteLine("Deserializing an instance of the object.")
        Dim fs As New FileStream(fileName, FileMode.Open)
        Dim reader As XmlDictionaryReader = _
           XmlDictionaryReader.CreateTextReader(fs, New XmlDictionaryReaderQuotas())
        Dim ser As New System.Runtime.Serialization.NetDataContractSerializer()
        
        ' Deserialize the data and read it from the instance.
        Dim deserializedPerson As Person = CType(ser.ReadObject(reader, True), Person)
        fs.Close()
        Console.WriteLine(String.Format("{0} {1}, ID: {2}", deserializedPerson.FirstName, deserializedPerson.LastName, deserializedPerson.ID))
    
    End Sub 
End Class

注解

安全性

NetDataContractSerializer 不安全。 有关详细信息,请参阅 BinaryFormatter 安全指南

NetDataContractSerializerDataContractSerializer 之间存在一个重要区别:NetDataContractSerializer 在序列化的 XML 中包含 CLR 类型信息;而 DataContractSerializer 不包含。 因此,只有在序列化和反序列化端使用相同的 CLR 类型时,才能使用 NetDataContractSerializer

序列化程序可以对已应用 DataContractAttributeSerializableAttribute 属性的类型进行序列化。 它还可以对用于实现 ISerializable 的类型进行序列化。

有关序列化的详细信息,请参阅 序列化和反序列化

与 XElement 不兼容

XElement 类用于写入 XML。 但是,NetDataContractSerializer 无法序列化该类型的实例。 因此,以下代码失败并出现异常:“根类型'System.Xml。NetDataContractSerializer 不支持 Linq.XElement',因为它是 IXmlSerializable IsAny=true ,并且必须写入其所有内容,包括根元素。

FileStream fs = new FileStream("mystuff.xml", FileMode.Create, FileAccess.ReadWrite);
XElement myElement = new XElement("Parent", new XElement("child1", "form"),
    new XElement("child2", "base"),
    new XElement("child3", "formbase")
    );
NetDataContractSerializer dcs = new NetDataContractSerializer();
dcs.WriteObject(fs, myElement);
Dim fs As New FileStream("mystuff.xml", FileMode.Create, FileAccess.ReadWrite)
Dim myElement As New XElement("Parent", New XElement("child1", "form"), _
    New XElement("child2", "base"), _
    New XElement("child3", "formbase") _
    )
Dim ser As New System.Runtime.Serialization. _
  NetDataContractSerializer()
ser.WriteObject(fs, myElement)

但是,如果将 XElement 用作类字段或属性的类型,则会序列化字段或属性包含的数据。 这是因为作为类成员时,数据不在类的顶层。

构造函数

NetDataContractSerializer()

初始化 NetDataContractSerializer 类的新实例。

NetDataContractSerializer(StreamingContext)

使用提供的流上下文数据初始化 NetDataContractSerializer 类的新实例。

NetDataContractSerializer(StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector)

使用提供的上下文数据初始化 NetDataContractSerializer 类的新实例;此外,还指定了对象中要序列化的最大项数、指定是否忽略额外数据的参数、程序集加载方法以及代理项选择器。

NetDataContractSerializer(String, String)

使用提供的 XML 根元素和命名空间初始化 NetDataContractSerializer 类的新实例。

NetDataContractSerializer(String, String, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector)

使用提供的上下文数据以及根名称和命名空间初始化 NetDataContractSerializer 类的新实例;此外,还指定了对象中要序列化的最大项数、指定是否忽略额外数据的参数、程序集加载方法以及代理项选择器。

NetDataContractSerializer(XmlDictionaryString, XmlDictionaryString)

使用两个类型为 NetDataContractSerializer 的参数(包含用于指定内容的根元素和命名空间)初始化 XmlDictionaryString 类的新实例。

NetDataContractSerializer(XmlDictionaryString, XmlDictionaryString, StreamingContext, Int32, Boolean, FormatterAssemblyStyle, ISurrogateSelector)

使用提供的上下文数据以及根名称和命名空间(作为 XmlDictionaryString 参数)初始化 NetDataContractSerializer 类的新实例;此外,还指定了对象中要序列化的最大项数、指定是否忽略找到的额外数据的参数、程序集加载方法以及代理项选择器。

属性

AssemblyFormat

获取一个指定用于查找和加载程序集的值。

Binder

获取或设置控制类加载的对象。

Context

获取或设置一个对象,它允许在序列化或反序列化时传递非常有用的上下文数据。

IgnoreExtensionDataObject

获取一个值,指定是否忽略对象扩展提供的数据。

MaxItemsInObjectGraph

获取对象中允许序列化的最大项数。

SurrogateSelector

获取或设置一个对象,以帮助格式化程序选择要序列化的代理项。

方法

Deserialize(Stream)

将 XML 文档或流反序列化为对象。

Equals(Object)

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

(继承自 Object)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type

(继承自 Object)
IsStartObject(XmlDictionaryReader)

使用指定的读取器确定是否将 XmlDictionaryReader 定位在可反序列化的对象上。

IsStartObject(XmlReader)

使用指定的读取器确定是否将 XmlReader 定位在可反序列化的对象上。

MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
ReadObject(Stream)

使用 Stream 读取 XML 流或文档,然后返回反序列化的对象。

(继承自 XmlObjectSerializer)
ReadObject(XmlDictionaryReader)

使用 XmlDictionaryReader 读取 XML 文档或流,然后返回反序列化的对象。

(继承自 XmlObjectSerializer)
ReadObject(XmlDictionaryReader, Boolean)

使用 XmlDictionaryReader 读取 XML 流或文档并返回反序列化的对象;还检查对象数据是否符合用于创建序列化程序的名称和命名空间。

ReadObject(XmlReader)

使用 XmlDictionaryReader 读取 XML 流或文档,并返回反序列化的对象。

ReadObject(XmlReader, Boolean)

使用 XmlDictionaryReader 读取 XML 流或文档并返回反序列化的对象;还检查对象数据是否符合用于创建序列化程序的名称和命名空间。

Serialize(Stream, Object)

使用指定的写入器序列化指定的对象图。

ToString()

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

(继承自 Object)
WriteEndObject(XmlDictionaryWriter)

使用 XmlDictionaryWriter 写入结束 XML 元素。

WriteEndObject(XmlWriter)

使用 XmlWriter 写入结束 XML 元素。

WriteObject(Stream, Object)

使用指定的 Stream 将对象的完整内容(开始、内容和结束)写入 XML 文档或流。

(继承自 XmlObjectSerializer)
WriteObject(XmlDictionaryWriter, Object)

使用指定的 XmlDictionaryWriter 将对象的完整内容(开始、内容和结束)写入 XML 文档或流。

(继承自 XmlObjectSerializer)
WriteObject(XmlWriter, Object)

使用指定的 XmlWriter 将对象的完整内容(开始、内容和结束)写入 XML 文档或流。

WriteObjectContent(XmlDictionaryWriter, Object)

使用 XmlDictionaryWriter 写入 XML 内容。

WriteObjectContent(XmlWriter, Object)

使用 XmlWriter 写入 XML 内容。

WriteStartObject(XmlDictionaryWriter, Object)

使用 XmlDictionaryWriter 写入开始 XML 元素。

WriteStartObject(XmlWriter, Object)

使用 XmlWriter 写入开始 XML 元素。

适用于

另请参阅