3

I am new to this site so I apologize for any improper formatting on my part.

I'm working on a project and am trying to Serialize a class that contains a List of type TDF_Test into an XML file but I keep getting the error "There was an error reflecting type LoadInformation".

I've read the Inner Exception as well and it says "There was an error reflecting property 'testList'". testList is the list of objects I'm trying to serialize.

Here is my class containing the List I want to serialize and save to an XML file.

namespace SPCTool.Core_Classes
{
    public class LoadInformation
    {
        public LoadInformation()
        { 
            testList = new List<TDF.TDF_Test>(); 
        }
        public List<TDF.TDF_Test> testList 
        { get; set; }
    }
}

Here is how I save it to the XML

LoadInformation info = new LoadInformation();
info.testList = someList; // someList is the same type as testList
SaveXML.SaveData(info, filename);

Here is the stacktrace:

at SPCTool.User_Interfaces.MainForm.saveToolStripMenuItem_Click(Object sender, EventArgs e) in 
M:\astburyj_TestProcess\IGXLTestProcess\TestProcess\tools\SPCReviewTool\SPCReviewTool\User Interface\MainForm.cs:line 940

Here is the class SaveXML

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace SPCTool.Core_Classes
{
    public class SaveXML
    {
        public static void SaveData(object obj, string filename)
        {
            XmlSerializer sr = new XmlSerializer(obj.GetType());
            TextWriter writer = new StreamWriter(filename);
            sr.Serialize(writer, obj);
            writer.Close();
        }
    }
}

I've done a lot of searching and haven't found a good solution. Does anyone know what I can do? Let me know if you need any other information or code.

Thanks a lot.


XmlSerializer wants to write data according to a schema it can figure out in advance by inspection of the types. "Object" simply does not figure in this. It wants to know the types. The "good solution" here is simply: stop trying to serialize unknown / unpredictable data, and switch to a simple DTO model that your chosen serializer can reason about. In particular, standard into / string / float / etc members, nested sub-objects where the type is advertised, subclasses / inheritance notified via XmlIncludeAttribute, etc. Lists, arrays, collections are all fine too, obviously - but while SomeType[] is fine, Array or object[] are not.

4

1 回答 1

1

XmlSerializer 希望根据可以通过检查类型预先确定的模式来写入数据。“对象”根本不在其中。它想知道类型。这里的“好解决方案”很简单:停止尝试序列化未知/不可预测的数据,并切换到您选择的序列化程序可以推理的简单 DTO 模型。特别是,标准 into / string / float / etc 成员,广告类型的嵌套子对象,通过 XmlIncludeAttribute 通知的子类/继承等。显然,列表,数组,集合也都很好 - 但是 SomeType[] 是很好, Array 或 object[] 不是。

于 2013-06-27T19:08:22.053 回答