![](/img/trans.png)
[英]XmlInclude to (De)Serialize Inherited Types in Separate Assemblies
[英]Serialize member types without using XmlInclude in .NET
我在.NET中执行XML序列化
我有以下课程
public class MainClass
{
public ClassA A;
}
public class ClassA { }
public class ClassB : ClassA { }
public class ClassC : ClassA { }
当我在MainClass的对象上调用XmlSerializer
Serialize
方法时,我得到了建议使用XmlInclude
属性的异常。 我不想使用attributes选项。
Serialize
方法有一个重载,它接受Type数组来指定正在进行序列化的类型的子类型(上例中的MainClass)。 使用此重载,我们可以避免使用XmlInclude
属性标记类。
是否可以对类型的成员(上例中的MainClass)进行类似的处理?
var ser = new XmlSerializer(typeof(MainClass),
new[] { typeof(ClassA), typeof(ClassB), typeof(ClassC) });
ser.Serialize(writer, new MainClass { A = new ClassB() });
结果:
<MainClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<A xsi:type="ClassB" />
</MainClass>
或者,您可以以编程方式添加属性:
var overrides = new XmlAttributeOverrides();
// Add [XmlElement]'s to MainClass.A
overrides.Add(typeof(MainClass), "A", new XmlAttributes
{
XmlElements = {
new XmlElementAttribute() { Type = typeof(ClassA) },
new XmlElementAttribute() { Type = typeof(ClassB) },
new XmlElementAttribute() { Type = typeof(ClassC) },
}
});
var ser = new XmlSerializer(typeof(MainClass), overrides, null, null, null);
ser.Serialize(writer, new MainClass { A = new ClassB() });
结果:
<MainClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ClassB />
</MainClass>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.