superuser
superuser

Reputation: 455

Getting exception when serialising custom collection

Below is the class I am trying to serialize.

I am getting exception during Serialize, It's working for Deserialize from 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;
    }
}

During Serialize method call I am getting exception message - There was an error generating the XML document.

I marked Serializable attribute on HasParentObservableCollection class

[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);
    }
}

Below is the serialization code

 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);

Upvotes: 0

Views: 47

Answers (1)

Ondrej Svejdar
Ondrej Svejdar

Reputation: 22064

Few issues here:

1) classes being serialized by XmlSerializer have to have public parametless constructor:

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

2) you're not serializing the type for which you've created the XmlSerializer instance

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

3) you can drop [Serializable] tag - that's ignored for xml serialization

Upvotes: 1

Related Questions