posted on Monday, September 27, 2004 8:23 AM
by
leon
XML Serialization basics
Here are a couple of basic (annoying) points about XML serialization. Consider two simple classes:
public class Container
{
private string m_s;
private int m_i;
private Child m_c = null;
public string S
{
get
{
return this.m_s;
}
set
{
this.m_s = value;
}
}
public int I
{
get
{
return this.m_i;
}
set
{
this.m_i = value;
}
}
public Child C
{
get
{
return this.m_c;
}
}
public Container(int i, string s, int ci, string cs)
{
this.m_i = i;
this.m_s = s;
this.m_c = new Child(ci, cs);
}
}
public class Child
{
private string m_cs;
private int m_ci;
public string CS
{
get
{
return this.m_cs;
}
set
{
this.m_cs = value;
}
}
public int CI
{
get
{
return this.m_ci;
}
set
{
this.m_ci = value;
}
}
public Child(int i, string s)
{
this.m_ci = i;
this.m_cs = s;
}
}
Can we serialize them? No, not yet. First of all we have to add public default constructor for each class being serialized:
public Container(){}
public Child(){}
OK, I can live with that. Let's try again:
class Test
{
public static void Main()
{
Container d = new Container(3, "abc", 4, "123");
StringWriter sw = new StringWriter();
XmlSerializer xs = new XmlSerializer(d.GetType());
xs.Serialize(sw, d);
Console.Write(sw.ToString());
}
}
Well, it is serialized now, but is not something missing? Where the child class has gone? Now, we have to keep in mind that XMLSerializer taking in account only public WRITABLE property. Property without getter will be skipped, even if it is of reference type and getter is totally unnecessary.
Final touch will give us desirable result:
public class Container
{
...
public Child C
{
get
{
return this.m_c;
}
set
{
}
}
...
}