C# 继承对象的XML反序列化
我有一个对象InputFile,它有数组和对象来保存文件的内容。我还有ABCFile和XYZFile,它们都是从InputFile继承的,它们将读取不同类型的文件并将它们存储到InputFile的投影成员中 由于这两个对象的序列化和反序列化都与父对象相同,因此我在父对象上实现了一个标准的XML序列化接口。在反序列化过程中,读取几个参数,调用read函数加载文件,然后反序列化完成 序列化非常有效,但列表的反序列化不起作用,因为反序列化程序调用父存根读取文件函数,而不是ABCFile或XYZFile 如何获得反序列化以识别要使用的对象的正确类型?我的列表可能混合了多种文件类型 谢谢 我用于序列化对象的代码:C# 继承对象的XML反序列化,c#,xml,inheritance,serialization,C#,Xml,Inheritance,Serialization,我有一个对象InputFile,它有数组和对象来保存文件的内容。我还有ABCFile和XYZFile,它们都是从InputFile继承的,它们将读取不同类型的文件并将它们存储到InputFile的投影成员中 由于这两个对象的序列化和反序列化都与父对象相同,因此我在父对象上实现了一个标准的XML序列化接口。在反序列化过程中,读取几个参数,调用read函数加载文件,然后反序列化完成 序列化非常有效,但列表的反序列化不起作用,因为反序列化程序调用父存根读取文件函数,而不是ABCFile或XYZFile
public class InputFileHolder : IXmlSerializable {
...
public void WriteXml(XmlWriter w) {
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer ifXml = new XmlSerializer(typeof(List<InputFile>));
ifXml.Serialize(w, InputFiles, ns);
//More serialization
}
当我自定义序列化列表时,如何维护对象类型
[XmlArray]
[XmlArrayItem(ElementName="ABCFile", Type=typeof(ABCFile))]
[XmlArrayItem(ElementName="XYZFile", Type=typeof(XYZFile))]
public List<InputFile> InputFileList
{
get;
set;
}
最后,serializedString的内容是:
<?xml version="1.0"?>
<InputFileHolder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<InputFileList>
<ABCFile>
<InputfileCommonProperty>This is a common property</InputfileCommonProperty>
<ABCSpecificProperty>This is a class specific property</ABCSpecificProperty>
</ABCFile>
</InputFileList>
</InputFileHolder>
看到了吗?序列化程序知道它是ABC文件,而不是一般的输入文件。感谢您的快速响应。生成的XML看起来仍然像:。如果我手动编辑XML以将InputFile更改为ABCFile,它将失败,并出现错误的XML。好的,它认为我已经发现了问题的根源。我的InputFileHolder版本有一个IXmlSerializable接口,我可以在其中自定义要序列化的参数读/写。如果我删除IXmlSerializable接口并让框架处理它,我会得到与您类似的XML,其中指定了对象类型。我需要有一个自定义读取,所以我需要修复写入。我将在主帖子中添加我的编写代码。
static void Main(string[] args)
{
InputFileHolder fileHolder = new InputFileHolder();
fileHolder.InputFileList.Add(
new ABCFile()
{
InputfileCommonProperty = "This is a common property",
ABCSpecificProperty = "This is a class specific property"
});
XmlSerializer serializer = new XmlSerializer(typeof(InputFileHolder));
MemoryStream memoryStream = new MemoryStream();
serializer.Serialize(memoryStream, fileHolder);
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
String serializedString = enc.GetString(memoryStream.ToArray());
}
<?xml version="1.0"?>
<InputFileHolder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<InputFileList>
<ABCFile>
<InputfileCommonProperty>This is a common property</InputfileCommonProperty>
<ABCSpecificProperty>This is a class specific property</ABCSpecificProperty>
</ABCFile>
</InputFileList>
</InputFileHolder>