Skip to content
Yanos edited this page Dec 6, 2014 · 1 revision

Deserialization

The serializer deserialize by instanciate an object and populate it, trying to apply each child element (attribute or node) to the writable member (field or property) with same name.

Population

The population follow some rules :

  • Each XML attribute are convert to a value type only (can't serizalize an object in an attribute XML).
  • Each XML node with child element is converted to an object.
  • Each XML node without child element is converted to a value type.

Usage

With this class

public class Cls
{
    // Private fields
    private String PValue1 = "Test";
    // Public property        
    public String Value1 { get { return PValue1; } set { PValue1 = value; } }
    // Public field
    public Double Value2 = 7.2;
    // Read only public property
    public int Value3 { get { return 2; } }
    // Protected property
    protected String Value4 { get; set; }
    // Object property
    public Cls Value5 { get; set; }
}

populate with this XML :

<Value>
  <Value1>String value</Value1>
  <VALUE2>987</VALUE2>
  <V3>XXXXX</V3>
</Value>
Cls c = new Cls();
serializer.Populate(xml, c);

'c' object contains now :

Value1 (string) = "String value"
Value2 (double) = 987
Value3 (int) = 2
Value5 (Cls) = {null}

We obtain the same object with deserialization :

Cls c1 = serializer.Deserialize<Cls>(xml);
Cls c2 = (Cls)serializer.Deserialize(xml, typeof(Cls));

If we deserialize XML without type, if the XML contains child elements it's deserialized to a IDictionary<String, Object>, else it try to convert to value.

var o = serializer.Deserialize(xml);

returns a dictionary :

"Value1" (String) => "String value"
"VALUE2" (Int64) => 987
"V3" (String) => "XXXXX"

and with a nested element

var o = serializer.Deserialize(XParse(
@"<Value>
<Value1>String value</Value1>
<VALUE2>987</VALUE2>
<V3>XXXXX</V3>
<V4 sv1=""One"">
    <sv2>Two</sv2>
    <sv3>123</sv3>
</V4>
</Value>"));

returns

"Value1" (String) => "String value"
"VALUE2" (Int64) => 987
"V3" (String) => "XXXXX"
"V4" (IDictionary<String,Object>) = {
  "sv1" (String) => "One"
  "sv2" (String) => "Two"
  "sv3" (Int64) => 123
}
Clone this wiki locally