开发者

Error when deserialize with XmlSerializer

I'm getting an exception with this code;

InnerException: System.InvalidOperationException

Message=The specified type was not recognized: name='Person',

namespace='', at "<"Contact xmlns=''>. Here is the relevant code I think.

The class Person is a bare class without any anotations and doesn't inherit from any interface.

How to make Deserialize recognize my classes? Thanks in advance.

public class Contacts : List<Contact.Contact>
{
    private void PopulateTypeList()
    {
        types.Add(typeof(Contact.Contact));
        types.Add(typeof(Contact.Company));
        types.Add(typeof(Contact.Person));
        types.Add(typeof(ContactData.Direction));
        types.Add(typeof(ContactData.email));
        types.Add(typeof(ContactData.Phone));
    }

    public void Load()
    {
        try
        {
            using (System.Xml.XmlReader stream = System.Xml.XmlReader.Create(fileName))
            {
                XmlSerializer xs = new XmlSerializer(typeof(List<Contact.Contact>));
                // this roundabout way is for making it possible for 开发者_Go百科this class to
                // inherit from List<Contact.Contact> and still use a method that
                // gives the stored data as an value in the object
here is error   List<Contact.Contact> data = 
                    (List<Contact.Contact>)xs.Deserialize(stream);
                this.Clear();
                this.AddRange(data);
            }
        }
        catch (System.IO.FileNotFoundException)
        {
            // do nothing; no file, new database
        }
    }

    public void Save()
    {
        using (System.Xml.XmlWriter stream = System.Xml.XmlWriter.Create(fileName))
        {
            XmlSerializer xs = 
                new XmlSerializer(typeof(List<Contact.Contact>), types.ToArray());
            List<Contact.Contact> data = this.ToList();
            xs.Serialize(stream, data);
        }
    }


Try passing the list of types to the serialiser you create for deserialisation:

XmlSerializer xs = new XmlSerialiser(typeof(List<Contact.Contact>), types.ToArray());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜