代码之家  ›  专栏  ›  技术社区  ›  Ray

如何在事先不知道类型的情况下反序列化XML?

  •  13
  • Ray  · 技术社区  · 16 年前

    [Serializable]
    public class Base
    {
    
        public string Property1 { get; set; }
        public int Property2 { get; set; }
    }
    
    [Serializable]
    public class Sub: Base
    {
        public List<string> Property3 { get; set; }
    
        public Sub():base()
        {
            Property3 = new List<string>();
        }        
    }
    

    Sub s = new Sub {Property1 = "subtest", Property2 = 1000};
    s.Property3.Add("item 1");
    s.Property3.Add("item 2");
    
    XmlSerializer sFormater = new XmlSerializer(typeof(Sub));
    using (FileStream fStream = new FileStream("SubData.xml", 
        FileMode.Create, FileAccess.Write, FileShare.None))
    {
        sFormater.Serialize(fStream, s);
    }
    

    如何反序列化它们,以便返回正确的类?

    XmlSerializer bFormater = new XmlSerializer(typeof (Base));
    Base newBase;
    using (FileStream fStream = new FileStream("BaseData.xml", 
        FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        newBase = (Base) bFormater.Deserialize(fStream);
    }
    

    除非我能够为从基派生的任何类传递一个XML文件,并创建正确的类。

    3 回复  |  直到 16 年前
        1
  •  10
  •   Kirtan    16 年前

    您可以读取XML文件的根节点,而不是使用switch语句,您可以这样编写代码-

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

        2
  •  8
  •   Anton Tykhyy    16 年前

    使用 [XmlInclude] 属性来告诉XML序列化程序有关派生类的信息,以便它可以确定要创建什么。最后一个代码段应该可以正常工作。

        3
  •  1
  •   Community CDub    8 年前

    据我所知,没有比这更简单的方法了。

    您可以查看此问题以了解一些详细信息: Serialise to XML and include the type of the serialised object