简体   繁体   English

序列化成员类型而不使用.NET中的XmlInclude

[英]Serialize member types without using XmlInclude in .NET

I am carrying out XML Serialization in .NET 我在.NET中执行XML序列化

I have the following class 我有以下课程

public class MainClass
{
    public ClassA A;
}

public class ClassA { }

public class ClassB : ClassA { }

public class ClassC : ClassA { }

When I am calling Serialize method of XmlSerializer on an object of MainClass, I am getting exception that is suggesting to make use of XmlInclude attribute. 当我在MainClass的对象上调用XmlSerializer Serialize方法时,我得到了建议使用XmlInclude属性的异常。 I don't want to use the attributes option. 我不想使用attributes选项。

Serialize method has an overload that takes array of Type to specify the sub-types of the type (MainClass in above example) on which serialization is being carried out. Serialize方法有一个重载,它接受Type数组来指定正在进行序列化的类型的子类型(上例中的MainClass)。 Using this overload we can avoid the need to mark the class with XmlInclude attribute. 使用此重载,我们可以避免使用XmlInclude属性标记类。

Can similar thing be done with members of the type (MainClass in above example) being serialized ? 是否可以对类型的成员(上例中的MainClass)进行类似的处理?

var ser = new XmlSerializer(typeof(MainClass),
    new[] { typeof(ClassA), typeof(ClassB), typeof(ClassC) });
ser.Serialize(writer, new MainClass { A = new ClassB() });

Result: 结果:

<MainClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <A xsi:type="ClassB" />
</MainClass>

Alternatively, you could add the attributes programmatically: 或者,您可以以编程方式添加属性:

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() });

Result: 结果:

<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM