使用 DataContractSerializer 序列化和反序列化多个对象

发布于 2024-12-11 03:47:56 字数 1740 浏览 0 评论 0原文

如何使用 DataContractSerializer 序列化和反序列化多个对象? 序列化很好,但是在反序列化过程中,我收到错误

“序列化操作失败。原因:反序列化 Serialization.Person 类型的对象时出错。有多个根元素。”

错误消息清楚地提到序列化文档没有根元素。 但我该如何克服这个问题呢?

代码如下:

[DataContract]
class Person {
    [DataMember(Name = "CustName")]
    internal string Name;
    public Person(string n) {Name = n;}
}

class Program {
    public static void Main() {
            WriteObject("d:\\temp\\DataContractExample.xml" , "Mary");
            WriteObject("d:\\temp\\DataContractExample.xml", "Joe");
            ReadObject("d:\\temp\\DataContractExample.xml");
    }

    public static void WriteObject(string path, string name) {
        Person p1 = new Person(name);
        FileStream fs = new FileStream(path, FileMode.Append);
        XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
        DataContractSerializer ser =  new DataContractSerializer(typeof(Person));
        ser.WriteObject(writer, p1);

        writer.Close();
        fs.Close();
    }
    public static void ReadObject(string path) {
        FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
        XmlDictionaryReader reader =
            XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());

        DataContractSerializer ser = new DataContractSerializer(typeof(Person));

        // Deserialize the data and read it from the instance.
        Person[] newPerson = (Person[])ser.ReadObject(reader);
        Console.WriteLine("Reading this object:");
        Console.WriteLine(String.Format("{0}", newPerson[0].Name));
        fs.Close();
    }

当我从 DataContractSerializer ser.ReadObject(reader) 读取数据时,我得到了上面提到的异常。 是否可以在使用 DataContractSerializer 存储多个对象时创建根元素?

How do I serialize and deserialize multiple objects using DataContractSerializer?
Serializing is fine, however during deserialization I get the error

"The serialization operation failed. Reason: There was an error deserializing the object of type Serialization.Person. There are multiple root elements."

The error message clearly mentions that there is no root element to the serialized document.
But how do i overcome this?

Here's the code:

[DataContract]
class Person {
    [DataMember(Name = "CustName")]
    internal string Name;
    public Person(string n) {Name = n;}
}

class Program {
    public static void Main() {
            WriteObject("d:\\temp\\DataContractExample.xml" , "Mary");
            WriteObject("d:\\temp\\DataContractExample.xml", "Joe");
            ReadObject("d:\\temp\\DataContractExample.xml");
    }

    public static void WriteObject(string path, string name) {
        Person p1 = new Person(name);
        FileStream fs = new FileStream(path, FileMode.Append);
        XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
        DataContractSerializer ser =  new DataContractSerializer(typeof(Person));
        ser.WriteObject(writer, p1);

        writer.Close();
        fs.Close();
    }
    public static void ReadObject(string path) {
        FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
        XmlDictionaryReader reader =
            XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());

        DataContractSerializer ser = new DataContractSerializer(typeof(Person));

        // Deserialize the data and read it from the instance.
        Person[] newPerson = (Person[])ser.ReadObject(reader);
        Console.WriteLine("Reading this object:");
        Console.WriteLine(String.Format("{0}", newPerson[0].Name));
        fs.Close();
    }

When I read from the DataContractSerializer, ser.ReadObject(reader), I get the exception that I mentioned above.
Is it possible to Create root element while storing multiple objects using DataContractSerializer?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北斗星光 2024-12-18 03:47:56

DataContractSerializer 适用于 xml 文档,因此需要单个顶级元素。最简单的方法是序列化 List,这应该可以避免这种情况。您还可以手动添加外部元素,也许在序列化期间使用 XmlReaderReadSubtree (尽管注意:这是一项丑陋的艰苦工作)。

不过,最简单的选择是从一开始就简单地序列化 List,然后反序列化为 List - 这将是一个 单个 xml 块,因此不会扰乱反序列化器。

DataContractSerializer works on xml documents, so expects a single top-level element. The simplest approach would be to serialize a List<Person>, which should avoid this. You could also add an outer element manually, perhaps using XmlReader and ReadSubtree during serialization (although note: this is ugly hard work).

The simplest option, though, is to simply serialize a List<Person> from the outset, and deserialize as a List<Person> - this will then be a single xml hunk, so won't upset the deserializer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文