NetDataContractSerializer 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
使用提供的 .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
- 继承
- 实现
示例
下面的示例代码演示一种名为 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 安全指南。
NetDataContractSerializer 与 DataContractSerializer 之间存在一个重要区别:NetDataContractSerializer 在序列化的 XML 中包含 CLR 类型信息;而 DataContractSerializer 不包含。 因此,只有在序列化和反序列化端使用相同的 CLR 类型时,才能使用 NetDataContractSerializer。
序列化程序可以对已应用 DataContractAttribute 或 SerializableAttribute 属性的类型进行序列化。 它还可以对用于实现 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
用作类字段或属性的类型,则会序列化字段或属性包含的数据。 这是因为作为类成员时,数据不在类的顶层。
构造函数
属性
AssemblyFormat |
获取一个指定用于查找和加载程序集的值。 |
Binder |
获取或设置控制类加载的对象。 |
Context |
获取或设置一个对象,它允许在序列化或反序列化时传递非常有用的上下文数据。 |
IgnoreExtensionDataObject |
获取一个值,指定是否忽略对象扩展提供的数据。 |
MaxItemsInObjectGraph |
获取对象中允许序列化的最大项数。 |
SurrogateSelector |
获取或设置一个对象,以帮助格式化程序选择要序列化的代理项。 |