简体   繁体   中英

C# Deserialize XML to correct class type

I am using the XmlSerializer to do some serialization work. I was wondering if it is possible to "generically" deserialize from the XmlDocuement.

Concrete: If I have an XML File I would watch the tag and compare it with my DTO Model. Is this possible (better: Does .NET support this?) ? Maybe using an XSD file or something?


Example (without generic deserialization):

        XmlDocument myDocument = new XmlDocument();
        myDocument.Load(xml);

        MemoryStream stream = new MemoryStream();
        myDocument.Save(stream);

        // Here I would like to use an interface instead and load the correct type of object.
        XmlSerializer serializer = new XmlSerializer(typeof(MyClass));

        MyClass myObject;

        serializer.Serialize(stream, myObject);

The only way is that you pre parse the xml file so you understand the class to create. You could also write somewhere (in the file extension? in an attribute of the first element of the doc?) the class type. When you have the class type you can create the right class via a switch statement (converting a string to a type) or via reflection (better).

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