考虑下面的类结构
[XmlInclude(typeof(DerivedClass))]
public class BaseClass
{
public string mem1;
public string mem2;
}
public class DerivedClass : List<BaseClass>
{
public string mem3;
public string mem4;
}
class Program
{
static void Main(string[] args)
{
DerivedClass obj = new DerivedClass();
obj.mem3 = "test3";
obj.mem4 = "test4";
BaseClass base11 = new BaseClass();
base11.mem1 = "test1";
base11.mem2 = "test2";
obj.Add(base11);
XElement
.Parse(XMLSerializerUtil.GetXMLFromObject(obj))
.Save(@"C:\new_settings1.xml");
}
}
给出的 GetXMLFromObject 代码如下
public static string GetXMLFromObject(object instance)
{
string retVal = string.Empty;
if (instance != null)
{
XmlSerializer xmlSerializer = new XmlSerializer(instance.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
xmlSerializer.Serialize(memoryStream, instance);
memoryStream.Position = 0;
retVal = new StreamReader(memoryStream).ReadToEnd();
}
}
return retVal;
}
即使添加了XmlInclude
属性,在生成的 XML 文件中,派生类成员也不存在。
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfBaseClass xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<BaseClass>
<mem1>test1</mem1>
<mem2>test2</mem2>
</BaseClass>
</ArrayOfBaseClass>
请让我知道,在生成的 XML 文件中包含派生类成员缺少什么。