This project is read-only.

Simplex Xml Serializer Compiler

In this exercise, we will build a mini compiler that takes a Type annotated with some System.Xml.Serialization attributes and generates a lightweight serializer on the fly.
What we want to do...
For the sake of simplicity we will support properties tagged with XmlAttributeAttribute and XmlElementAttribute, in which cases the property can be an array as well. Let's this with an example:

public class Foo
    public string Name {get;set;}

    public Bar MyBar {get;set;}

    public class Bar
        public Foo[] Foes {get;set;}

Given a little object tree, we'll expect the serializer to produce a nice xml output:

Foo foo = new Foo();
foo.Name = "Hello";
foo.MyBar = new Bar();
foo.MyBar.Foes = new Foo[]{ new Foo(), new Foo(), null };
foo.MyBar.Foes[0].Name = "foo1";
foo.MyBar.Foes[1].Name = "foo2";

<Foo Name="Hello">
      <Foo Name="foo1" />
      <Foo Name="foo2" />

Designing the serializer

Given the type Foo, we expect the compiler to generate a method for each type Foo and Bar that works directly on a XmlWriter:

void WriteFoo(XmlWriter writer, Foo target)
    writer.WriteAttributeString("Name", target.Name);
    if (target.Bar != null)
        WriteBar(writer, target.Bar);

void WriteBar(XmlWriter writer, Bar bar)
    if (bar.Foes!=null)
        foreach(Foo foo in bar.Foes)
            if (foo!=null)
                WriteFoo(writer, foo); 

Building the compiler

The compilation process is a 2-pass algorithm:
  • collect the list of types that might be serialized by walking the property types. For each type, define new {{WriteXXX} method,
  • bake the body for each WriteXXX method

The full source of this sample is in the source distribution. Let's focus on interresting parts, i.e. generating the method bodies.
  • Write a property as argument:
    • fetch the property value,
    • if the property is not a string, convert the value to string using XmlConvert,
    • invoke XmlWriter.WriteAttributeString
PropertyInfo property = ...;
XmlAttributeAttribute xmlAttribute = Attribute.GetCustomAttribute(property, typeof(XmlAttributeAttribute)) 
    as XmlAttributeAttribute; // is this an attribute?
if (xmlAttribute!=null)
    // var value = target.Foo;
    Expression pvalue= Expr.Param(value).GetProperty(property);
    if (property.PropertyType != typeof(string))
        // WriteAttributeString works with string
        // string value = XmlConvert.ToString(target.Foo);
        pvalue = Expr.InvokeMethod(
            typeof(XmlConvert), "ToString", BindingFlags.Public | BindingFlags.Static, pvalue);

     // writer.WriteAttributeString("Foo", XmlConvert.ToString(target.Foo);
             "WriteAttributeString", Expr.Prim(property.Name), pvalue)
  • Write an element:
    • if the element is not null, call the corresponding WriteXXX method:
// types is a dictionary containing the WriteXXX methods
MethodFactoryBase method = this.types[property.PropertyType];

// WriteFoo(writer, value.Foo); 
MethodInvokeExpression invoke = new MethodInvokeExpression(
    null, // static method

// if (value.Foo != null) WriteFoo(writer, value.Foo);
        Expr.Inequality(Expr.Param(value).GetProperty(property), Expr.Null),
        ) // If
    ); // Add

  • Write an array of elements:
    • check that the array is not null,
    • create a foreach loop that invokes the corresponding WriteXXX method. Even better, Toad supports adding a condition on the foreach (i.e. foreach ... where) so we can filter out null elements in the array:
//  foreach(Foo foo in target.Foes where foo != null)
ForEachStatement fe = Stm.ForEach(
// where x != null                               
fe.WhereExpression = Expr.Inequality(Expr.Var(fe.Variable), Expr.Null);

// WriteFoo(writer, foo);    
MethodFactoryBase method = this.types[property.PropertyType.GetElementType()];
MethodInvokeExpression invoke = new MethodInvokeExpression(...);

// foreach(...) { WriteFoo(writer, foo); }
fe.Body = Stm.Expr(invoke);

// if (value.Foes != null) { foreach... }
        Expr.Inequality(Expr.Param(value).GetProperty(property), Expr.Null),

That's it. Glue the pieces together and let Toad bake the IL for you :)

Last edited May 20, 2007 at 6:00 PM by pelikhan, version 9


No comments yet.