您可以将要“包含”的类型传递给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();
}
}