简体   繁体   中英

serialize derived xml to base class in C#

I have a base class like :

public class Sensor
{
        public void Serialize(string path)
        {
            try
            {
                System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(this.GetType());
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(System.IO.Path.GetFullPath(path)))
                {
                    xml.Serialize(file, this);
                }
            }
            catch (Exception e)
            {
                ;
            }
        }

        public static T Deserialize<T>(string path)
        {
            T loaded = default(T);
            try
            {
                System.Xml.Serialization.XmlSerializer deserializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                using (StreamReader reader = new StreamReader(path))
                {
                    loaded = (T)deserializer.Deserialize(reader);
                }
            }
            catch (Exception e)
            {
                ;
            }
            return loaded;
        }

}

Then I have a couple of classes that derive from this:

public TemperatureSensor : Sensor {}

public PositionSensor :Sensor{}

They share some common interfaces but also implement things differently. I have a SensorController that contains a List<Sensor> with a mixture of different sensors. I want to save them to XML files and load them afterwards.

I tried a simple:

public void Load()
        {
            var files = Directory.GetFiles(directory, "*.xml");
            foreach(var file in files)
            {
                var p = CodePuzzle.Deserialize<Puzzle>(file);
            }
        }

The problem is that when the deserializer finds the <PositionSensor> it crashes ( Unexpected <PositionSensor> at 2,2 ).. I guess it was expecting <Sensor>

How can that be done?? Loading each Sensor in the sub-class it was originally stored in??

First you should add the tag [XmlInclude(typeof(DerivedClass))] to the base Class. So it looks like:

[Serializable]
[XmlInclude(typeof(TemperatureSensor))]
[XmlInclude(typeof(PositionSensor))]
public Class Sensor 
   ....

Then when you save to xml file any of the derived class, save them as Sensor , not as the derived class.

var myTemp = new TemperatureSensor();
Sensor.saveToXML(myTemp,"myTemp.xml")

Then when reading the xml´s in as Sensor, you can still identify the subclass they actually belong to.

Sensor myImportedSensor = Sensor.Load("myTemp.xml")
// myImportedSensor is Sebsir returns true
// AND
// myImportedSensor is TemperatureSensor returns also true

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