Question

I have 2 class:

public class ClassA

public class ClassB (from another namespace) : ClassA

I have xml files fill with ClassA.

How to cast it to ClassB while deserialization.

is it possible ??

Was it helpful?

Solution

I tried this solution, i.e. applying an XmlRoot element specifying the same element name as the one in ClassA.
This should work:

using System;
using System.IO;
using System.Xml.Serialization;

[XmlRoot("ClassA")]
public class ClassA {
    [XmlElement]
    public String TextA {
        get;
        set;
    }
}

[XmlRoot("ClassA")] // note that the two are the same
public class ClassB : ClassA {
    [XmlElement]
    public String TextB {
        get;
        set;
    }

}

class Program {
    static void Main(string[] args) {

        // create a ClassA object and serialize it
        ClassA a = new ClassA();
        a.TextA = "some text";

        // serialize
        XmlSerializer xsa = new XmlSerializer(typeof(ClassA));
        StringWriter sw = new StringWriter();
        xsa.Serialize(sw, a);

        // deserialize to a ClassB object
        XmlSerializer xsb = new XmlSerializer(typeof(ClassB));
        StringReader sr = new StringReader(sw.GetStringBuilder().ToString());
        ClassB b = (ClassB)xsb.Deserialize(sr);

    }
}

OTHER TIPS

You can't cast a base class to a derived class - you can only cast derived classes back to their base classes (one-way).

When creating the XmlSerialiser, you need to do it from your ClassB, it will then deserialise as the class you wish.

It would be invalid to cast a base class as an instance of a derived class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top