Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 953
One Monkey Avatar asked Oct 26 '11 10:10

One Monkey


People also ask

What does it mean to deserialize XML?

Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.

Can I make XmlSerializer ignore the namespace on Deserialization?

Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization.


2 Answers

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());
}
like image 69
Tim Rogers Avatar answered Oct 13 '22 02:10

Tim Rogers


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());
    }
}
like image 22
Ray Avatar answered Oct 13 '22 02:10

Ray