One Monkey
One Monkey

Reputation: 713

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

I have a class:

public class MyClass
{
   public MyClass(){}
}

I would like to be able to use an XMLSeralizer to Deserialize an XDocument directly in the constructor thus:

public class MyClass
{
   private XmlSerializer _s = new XmlSerializer(typeof(MyClass));

   public MyClass(){}
   public MyClass(XDocument xd)
   {
      this = (MyClass)_s.Deserialize(xd.CreateReader());
   }
}

Except I am not allowed to assign to "this" within the constructor.

Is this possible?

Upvotes: 13

Views: 18955

Answers (4)

Jimbo
Jimbo

Reputation: 22984

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));
   }
}

Upvotes: 1

Ray
Ray

Reputation: 46595

It's more standard to use a static load method.

public class MyClass
{
    public static MyClass Load(XDocument xDoc)
    {
        XmlSerializer _s = new XmlSerializer(typeof(MyClass));
        return (MyClass)_s.Deserialize(xDoc.CreateReader());
    }
}

Upvotes: 7

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56182

Is better use some kind of factory, e.g.:

public static MyClass Create(XDocument xd)
{
    XmlSerializer _s = new XmlSerializer(typeof(MyClass));
    return (MyClass)_s.Deserialize(xd.CreateReader());
}

Upvotes: 5

Tim Rogers
Tim Rogers

Reputation: 21713

No, it's not possible. Serializers create objects when they deserialize. You've already created an object. Instead, provide a static method to construct from an XDocument.

public static MyClass FromXml (XDocument xd)
{
   XmlSerializer s = new XmlSerializer(typeof(MyClass));
   return (MyClass)s.Deserialize(xd.CreateReader());
}

Upvotes: 35

Related Questions