【问题标题】:Getting exception when serialising custom collection序列化自定义集合时出现异常
【发布时间】:2017-11-23 02:39:05
【问题描述】:

下面是我要序列化的类。

我在序列化期间遇到异常,它适用于从 xml 进行反序列化。

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class Organization
{
    private string _name;

    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
        }
    }

    private HasParentObservableCollection<Employee> _emp;

    [System.Xml.Serialization.XmlElementAttribute("Employee")]
    public HasParentObservableCollection<Employee> Emp
    {
        get
        {
            return _emp;
        }
        set
        {
            _emp = value;
        }
    }

    public Organization(string name, HasParentObservableCollection<Employee> emp)
    {
        Emp = emp;
        Name = name;
    }
}

在序列化方法调用期间,我收到异常消息 - There was an error generating the XML document.

我在HasParentObservableCollection 类上标记了Serializable 属性

[Serializable]
public class HasParentObservableCollection<T> : ObservableCollection<T>
{
    protected override void InsertItem(int index, T item)
    {
        //set the parent object when a new item is added to our collection
        if (item != null && item is IHasParent)
            (item as IHasParent).Parent = this;

        base.InsertItem(index, item);
    }
}

下面是序列化代码

 Organization org1 = new Organization("org11", new HasParentObservableCollection<Employee>() { new Employee("AA", "AA"), new Employee("AA", "AA") });
 Organization org2 = new Organization("org22", new HasParentObservableCollection<Employee>() { new Employee("BB", "BB"), new Employee("AA", "AA") });
 ObservableCollection<Organization>() Org = new ObservableCollection<Organization>() { org1, org2};


XmlSerializer serializer = new XmlSerializer(typeof(Organization));
StringWriter sw = new StringWriter();
XmlTextWriter tw = new XmlTextWriter(sw);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
serializer.Serialize(tw, Org, ns);

【问题讨论】:

  • 您使用的是哪个序列化程序?你能包括做序列化的代码片段吗?
  • 更新代码...

标签: c# .net wpf serialization


【解决方案1】:

这里有几个问题:

1) 被XmlSerializer 序列化的类必须有公共无参数构造函数:

public class Organization { public Organization() {} ... }
public class Employee { public Employee() {} ... }

2) 您没有序列化您为其创建 XmlSerializer 实例的类型

var serializer = new XmlSerializer(typeof(ObservableCollection<Organization>));

3) 你可以删除[Serializable] 标记 - 对于 xml 序列化,它会被忽略

【讨论】:

    猜你喜欢
    • 2015-03-08
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 2012-11-29
    相关资源
    最近更新 更多