考虑以下类结构
[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;
}
即使在生成的XML文件中添加XmlInclude
属性后,派生的类成员也不存在。
<?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文件中包含派生类成员所缺少的内容。
答案 0 :(得分:3)
问题在于:
DerivedClass : List<BaseClass>
对于XmlSerializer
,项目 列表 exclusive-or 一个实体。如果它看起来像一个列表,那么仅列表项被序列化; “list”本身的成员未序列化。基本上,不要这样做。 封装列表而不是从列表中派生:
另请注意,[XmlInclude(...)]
会期望DerivedClass : BaseClass
。所以,像:
public class SomeType // note DOES NOT INHERIT
{
private readonly List<SomeOtherType> items = new List<SomeOtherType>();
public List<SomeOtherType> Items { get { return items; } }
[XmlElement("mem3")] public string Mem3 {get;set;}
[XmlElement("mem4")] public string Mem4 {get;set;}
}
public class SomeOtherType
{
[XmlElement("mem1")] public string Mem1 {get;set;}
[XmlElement("mem2")] public string Mem2 {get;set;}
}