How do I deserialize XML into an object using a constructor that takes an XDocument?

前端 未结 4 1230
长情又很酷
长情又很酷 2020-12-18 22:29

I have a class:

public class MyClass
{
   public MyClass(){}
}

I would like to be able to use an XMLSeralizer to Deserialize an XDocument d

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-18 22:58

    I wanted to do the same thing and decided to do the following:

    public class MyClass
    {
       public MyClass(){
       }
    
       public MyClass(XDocument xd)
       {
          var t = typeof(MyClass);
          var o = (MyClass)new XmlSerializer(t).Deserialize(xd.CreateReader());
    
          foreach (var property in t.GetProperties())
              property.SetValue(this, property.GetValue(o));
       }
    }
    

提交回复
热议问题