简体   繁体   中英

Serialize member types without using XmlInclude in .NET

I am carrying out XML Serialization in .NET

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. I don't want to use the attributes option.

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. Using this overload we can avoid the need to mark the class with XmlInclude attribute.

Can similar thing be done with members of the type (MainClass in above example) being serialized ?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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