簡體   English   中英

如何使用XmlInclude動態指定類型?

[英]How to use XmlInclude to specify types dynamically?

我有以下這些類:

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屬性可以指定靜態未知的類型。

我怎么解決這個問題?

這是因為您的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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM