How do I deserialize XML without knowing the type beforehand?

后端 未结 3 1980
囚心锁ツ
囚心锁ツ 2020-12-11 01:38

Say I have a couple of basic objects like so:

[Serializable]
public class Base
{

    public string Property1 { get; set; }
    public int Property2 { get; s         


        
相关标签:
3条回答
  • 2020-12-11 02:04

    Use the [XmlInclude] attribute on your base class to tell the XML serializer about derived classes, so it can figure out what to create. Your last code snippet should then work correctly.

    0 讨论(0)
  • 2020-12-11 02:04

    As far as I know, there is no simplier way to do this.

    I personally prefer a more generic solution (as I have to serialize a lot of various classes in my code): to keep type name serialized together with the value.

    You can take a look at this question for some details: Serialise to XML and include the type of the serialised object

    0 讨论(0)
  • 2020-12-11 02:09

    You can read the XML file's root node and instead of using a switch statement, you can write your code like this -

    Type yourType = Type.GetType("Your Type");
    XmlSerializer xs = new XmlSerializer(yourType);
    

    I don't think there's any way other than reading the XML because if you don't know the type, you can't do anything.

    0 讨论(0)
提交回复
热议问题