在没有XmlInclude的情况下序列化数据

时间:2013-04-08 19:55:38

标签: xml serialization xml-serialization

我试图在我创建的存储库类中引用我的派生类。

以下是代码:

[XmlInclude(typeof(Case1))]
[XmlInclude(typeof(Case2))]
[XmlInclude(typeof(Case3))]
public class FileRepo: IFileRepo
{
    public string Name { set; get; }
    public DateTime Time { get; set; }
    public bool Correct{ get; set; }

    public void SerializetoXml(IFileRepo repo)
    {

        var filename = string.Format("{0}__{1}", DateTime.Now.ToString("yyMMddhhss"), "Log.xml");
        var path =
            @"C:\Temp;
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
        var fullpath = Path.Combine(path, filename);


        var serializer = new XmlSerializer((typeof(FileRepo))); 
        var textwriter = new StreamWriter(fullpath);

        serializer.Serialize(textwriter, repo);
        textwriter.Close();  
    }
}

基本上我试图'引用'所有这些类而不必为每个类放置XmlInclude。请列出任何示例或参考资料来解决此问题。

1 个答案:

答案 0 :(得分:2)

您可以传递您想要的类型"包括"到XmlSerializer构造函数,如下所示。

public class StackOverflow_15887772
{
    //[XmlInclude(typeof(Case1))]
    //[XmlInclude(typeof(Case2))]
    //[XmlInclude(typeof(Case3))]
    public class FileRepo
    {
        public string Name { set; get; }
        public DateTime Time { get; set; }
        public bool Correct { get; set; }
    }

    public class Case1 : FileRepo { public string Data { get; set; } }
    public class Case2 : FileRepo { public string Data { get; set; } }
    public class Case3 : FileRepo { public string Data { get; set; } }

    public static void SerializetoXml(FileRepo repo)
    {
        MemoryStream ms = new MemoryStream();
        var serializer = new XmlSerializer(typeof(FileRepo), new Type[] { typeof(Case1), typeof(Case2) });
        serializer.Serialize(ms, repo);
        Console.WriteLine("Serialized type {0}:", repo.GetType().Name);
        Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
    }

    public static void Test()
    {
        SerializetoXml(new Case1 { Data = "case 1", Correct = true, Name = "goo", Time = DateTime.UtcNow });
        SerializetoXml(new Case2 { Data = "case 2", Correct = true, Name = "goo", Time = DateTime.UtcNow });
        try
        {
            // this will fail, Case3 isn't passed to the XmlSerializer .ctor
            SerializetoXml(new Case3 { Data = "case 3", Correct = true, Name = "goo", Time = DateTime.UtcNow });
        }
        catch (Exception ex)
        {
            Console.WriteLine("{0}: {1}", ex.GetType().FullName, ex.Message);
            Exception inner = ex.InnerException;
            while (inner != null)
            {
                Console.WriteLine("    {0}: {1}", inner.GetType().FullName, inner.Message);
                inner = inner.InnerException;
            }
        }
    }
}

我知道这是旧的,但是我使用这里的信息来创建一个适用于我的通用方法,如下所示:

    public static string toXML<T>(this T obj)
    {
        using (StringWriter writer = new StringWriter())
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T), new Type[] { obj.GetType() });
            serializer.Serialize(writer, obj);
            return writer.ToString();
        }
    }