序列化自定义集合时获取异常

时间:2017-06-20 13:49:45

标签: c# .net wpf serialization

以下是我要序列化的课程。

我在Serialize期间遇到异常,它正在从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;
    }
}

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

我在Serializable

上标记了HasParentObservableCollection属性
[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);

1 个答案:

答案 0 :(得分: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序列化

将被忽略