Brij
Brij

Reputation: 13151

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 ?

Upvotes: 0

Views: 675

Answers (1)

Markus Jarderot
Markus Jarderot

Reputation: 89221

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>

Upvotes: 2

Related Questions