0

我有我使用的这些类:

namespace defaultNamespace
{
    ...
    public class DataModel
    {
    }
    public class Report01
        {get; set;}
    public class Report02
        {get; set;}
}

我有一个方法可以创建下面的 XML。

public XmlDocument ObjectToXml(object response, string OutputPath)
{
    Type type = response.GetType();
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
    serializer.Serialize(writer, response);
    XmlDocument xmldoc = new XmlDocument();
    stream.Position = 0;
    StreamReader sReader = new StreamReader(stream);
    xmldoc.Load(sReader);
    stream.Position = 0;
    string tmpPath = OutputPath;
    while (File.Exists(tmpPath))
    {
        File.Delete(tmpPath);
    }
    xmldoc.Save(tmpPath);
    return xmldoc;
}

我有两个具有 Report01 和 Report02 对象的列表。

List<object> objs = new List<object>();
List<object> objs2 = new List<object>();

Report01 obj = new Report01();
obj.prop1 = "aa";
obj.prop2 = "bb";
objs.Add(obj);

Report02 obj2 = new Report02();
obj2.prop1 = "cc";
obj2.prop2 = "dd";
objs2.Add(obj2);

当我尝试像这样创建 XML 时:

ObjectToXml(objs, "c:\\12\\objs.xml");
ObjectToXml(objs2, "c:\\12\\objs2.xml");

我看到了这个例外:

不需要类型“Report01(或 Report02)”。使用 XmlInclude 或 SoapInclude 属性指定静态未知的类型。

我怎么解决这个问题?

4

1 回答 1

0

这是因为您response.GetType()实际返回List<object>类型,然后您尝试序列化非预期类型。Object对您的类型和序列化程序一无所知,因为Object无法序列化您的未知类型。

您可以将 BaseClass 用于您的报告并XmlInclude解决此异常:

[XmlInclude(typeof(Report01)]
[XmlInclude(typeof(Report02)]
public class BaseClass { }
public class Report01 : BaseClass { ... }
public class Report02 : BaseClass { ... }

List<BaseClass> objs = new List<BaseClass>();
List<BaseClass> objs2 = new List<BaseClass>();
// fill collections here
ObjectToXml(objs, "c:\\12\\objs.xml");
ObjectToXml(objs2, "c:\\12\\objs2.xml");
于 2016-01-12T11:54:31.857 回答