2

我正在尝试使用序列化和自定义类创建一个 xml 文件,但出现异常:“生成 xml 文档时出错。”

我用一个字符串列表试过它,它可以工作,但不能用自定义类型......有没有人有 idia 为什么?

public class MyXML
{
    List<MyClass> Mylist;
    public XmlSerializer serialize;

    public MyXML()
    {
        Mylist=new List<MyClass>();
        serialize = new XmlSerializer(typeof(List<MyClass>));
    }

    public void Save(List<MyClass> newList)
    {
        using (FileStream writer = File.OpenWrite(Directory.GetCurrentDirectory()  + "/files/MyNewFile.xml"))
        { serialize.Serialize(writer, newList); }
    }
}
4

1 回答 1

0

Here's the trick: take your current code and wrap it in:

try {
    // create and use serializer
} catch(Exception ex) {
    while(ex != null) {
        Debug.WriteLine(ex.Message);
        ex = ex.InnerException;
    }
    throw;
}

XmlSerializer actually gives you very detailed reasons when it can't serialize/deserialize something - but they are hidden in the inner-exceptions. With the above, you'll be able to see what the problem is in the debug output.

Usual suspects:

  • type must be fully-public
  • type must have a public parameterless constructor
  • if the actual instance is a sub-class, that must be declared in advance
于 2012-12-09T13:42:13.347 回答