以下是我要序列化的课程。
我在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);
答案 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序列化