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?
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.
Yes, you can tell the XmlSerializer to ignore namespaces during de-serialization.
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());
}
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With